More and more when I need to automate backup tasks or perform devops tasks, it becomes essential for me to verify the existence or not of specific files or directories. In Bash, you can use the TEST command to check whether a file exists and determine the type of the file.
The test command takes one of the following syntax forms:
test EXPRESSION
[ EXPRESSION ]
[[ EXPRESSION ]]
If you want your script to be portable, you should prefer using the old test [ command, which is available on all POSIX shells. The new upgraded version of the test command [[ (double brackets) is supported on most modern systems using Bash, Zsh, and Ksh as a default shell.
Check if File exists
When we want to check if a file exists, the most used FILE operators are -e and -f. The first -e we will use to check if a file exists regardless of type. Now if we want to check that a file is a specification, not a directory or a device, use the second -f .
The most common option to check whether a file exists or not is to use the TEST command in combination with the if statement. Let’s say we want to check if there is a backup file from the previous day before executing an action:
Option using TEST
FILE=/backup_dir/file_$(date -d yesterday +%Y_%m_%d) if test -f "$FILE"; then echo "$FILE exists." fi
Option using [ ]
FILE=/backup_dir/file_$(date -d yesterday +%Y_%m_%d) if [ -f "$FILE" ]; then echo "$FILE exists." fi
Option using [[ ]]
FILE=/backup_dir/file_$(date -d yesterday +%Y_%m_%d) if [[ -f "$FILE" ]]; then echo "$FILE exists." fi
If our intention is to perform different actions depending on whether or not the file exists, we can make use of THEN and ELSE
FILE=/backup_dir/file_$(date -d yesterday +%Y_%m_%d) if [ -f "$FILE" ]; then echo "$FILE exists." else echo "$FILE does not exist." fi
Check if Directory exist
The operators -d allows you to check if a directory exist or not.
For example to check whether the /backup_dir directory exist you would use:
FILE=/backup_dir/ if [ -d "$FILE" ]; then echo "$FILE is a directory." fi
You can also use the double brackets [[ ]] instead of a single one [ ].
Check if File or Directory does not exist
Using the exclamation mark !, as in most programming languages, we can negate an expression.
Check if File does not exist
FILE=/backup_dir/file_$(date -d yesterday +%Y_%m_%d) if [ ! -f "$FILE" ]; then echo "$FILE does not exist." fi
Check if Directory does not exist
FILE=/backup_dir/ if [ ! -d "$FILE" ]; then echo "$FILE does not exist." fi
Concluding
This guide, like most of the posts on this blog, are the result of questions that I have had while developing some tasks in my daily work. I hope this solution will simplify other people’s work.
If you have any questions or suggestions, you can leave a comment.