How To Check If a File or Directory Exists Using Shell Script?

One of the common tasks in shell scripting in Linux/Mac OS, checking if a file or directory exists already and to create the file/directory if it does not exists. Here is how to check if a file or directory exists in Linux shell script.

The basic syntax to check if a file exists is

[-f filename ]

and the basic syntax to check is a directory exists is

[ -d dirname ]

One can use the basic syntax with if condition in the shell script to do something if the file/directory exists.  For example, here is piece of shell script, that prints it if the file/directory exists.

if [ -f binom.py ]
then
    echo 'binom.py exists'
fi

If the filename/dirname is simple, then it will check in the current working directory. You can give a full path to the file or directory to check for file/directory in different directory. Remember the space after opening and closing the bracket in the syntax. If there is no space, the shell script will compain something like “[-f: command not found” or ” [: missing `]'”.

Here is the shell script to check if a directory exists

if [ -d Codes ]
then
    echo 'Codes exists'
fi