Checking if a File or Directory Exists in a Bash Script

One common thing I find myself needing to do in Linux bash shell scripting is to check if a file or directory exists. The opposite is equally important – to see if a file does not exist. This can be used to check if a previous install or config has been done or not, or to check for certain conditions.

This is done using the Linux “test” command and is generally done in conjunction with a simple “if fi” statement with some action taken as a result. There are several file operators that can be used with test, but the most common are -f for standard files and -d for directories. There is also -e that will check for any type, including non-standard files (think devices listed in /dev for example) as well as directories. You can find a full list of file operators on the test man page.

It is important to understand that the test command will not output anything to stdout – it relies on exit codes to report a success or failure. For the purposes of file and directory checks, an exit code of 0 is “success” and 1 if “failure”. To see the exit code of the last command run, you can use echo $?.

Check if a file /opt/guest-cust/readme.md exists:

test -f /opt/guest-cust/readme.md
echo $?
0

Because an exit code of 0 was returned, we know that the file exists.

Continue reading “Checking if a File or Directory Exists in a Bash Script”