Shell script check if file or directory exists

scripting

In shell scripting we often need to check if file or directory exists and take appropriate action. This post show you how to check it and how this check use in your script.

For checking we will use file test operators -f for file and -d for directory, which return TRUE if file or directory exists.

Here is the script:

system1 # cat checkfd.sh
#!/bin/sh

#
# example how to check if exists directory or file
#

FILE=/scripts/test/test.txt
DIR=/scripts/test

if [ ! -f $FILE ]
then
        echo "file " $FILE " does not exist.";
else
        echo "file " $FILE " exists.";
fi

echo "========";

if [ ! -f $DIR ]
then
        echo "file " $DIR " does not exist.";
else
        echo "file " $DIR " exists.";
fi

echo "========";

if [ ! -d $DIR ]
then
        echo "directory " $DIR " does not exist.";
else
        echo "directory " $DIR " exists.";
fi

echo "========";

if [ ! -d $FILE ]
then
        echo "directory " $FILE " does not exist.";
else
        echo "directory " $FILE " exists.";
fi


system1 #

And here is output of the script.

system1 # ll /scripts/test/test.txt
-rw-r--r-- 1 root root 41 Aug 19 08:04 /scripts/test/test.txt
system1 # ll -d /scripts/test
drwxr-xr-x 12 root root 4096 Aug 19 08:04 /scripts/test
system1 #
system1 # ./checkfd.sh
file  /scripts/test/test.txt  exists.
========
file  /scripts/test  does not exist.
========
directory  /scripts/test  exists.
========
directory  /scripts/test/test.txt  does not exist.
system1 #

Leave a Reply