How to check if a file exist in a Bash Script?
Data in Unix is organized into files. Several files are organized into directories. All directories are structured in a tree-like structure, called as the filesystem.
In Unix, most of the time, you end up working with files and perform operations on the same - like listing files, copying or moving files, deleting files etc.,
So, let's see jpw we can check if a file exists or not in a given path.
Check if a file exists in Bash Script
We use the if
command to check if a file exists or not. if
performs a conditional check on the command that goes inside the brackets [ ]
.
if [ -f "$FILE_PATH" ]; then
# If the $FILE_PATH exist, code inside the block will get executed, for example:
echo "File $FILE_PATH exist";
fi
Check if a file does not exists in Bash Script
Here we are checking the error condition or the negative condition if the file does not exist.
if [ ! -d "$FILE_PATH" ]; then
# If the $FILE_PATH does not exist, code inside the block will get executed, for example:
echo "File $FILE_PATH does not exist";
fi
Are you looking for the scenario if a directory exist or not in bash scripts?
There is also a shorthand notation to check if a file exist or not:
Shorthand to check if a file exist
[ -f "$FILE_PATH" ] && echo "File $FILE_PATH exist";
Shorthand to check if a file does not exist
[ ! -f "$FILE_PATH" ] && echo "File $FILE_PATH does not exist";
You can have any statement after the &&
symbol.
The above code is an ideal way to check if a file exists in a given path or not.