[BASH] Check if a file or dir exists

Run the following code to test a file and dir checking.

#!/bin/bash
FILE="/root/test.txt"
DIRECTORY="/sbin"

# IF FILE EXISTS
if [ -f $FILE ]; then
    echo "File $FILE exists."
fi


# IF FILE DOES NOT EXIST
if [ ! -f $FILE ]; then
    echo "File $FILE does not exist."
fi


# IF DIR EXISTS
if [ -d "$DIRECTORY" ]; then
    echo "Dir $DIRECTORY exists."
fi


# IF DIR DOES NOT EXIST
if [ ! -d "$DIRECTORY" ]; then
    echo "Dir $DIRECTORY does not exist."
fi

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.