Published on

# How to check if a file exist in a Bash Script?

Checking if a file exist or not can be easily done with the script below

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  Or to check if a file doesn't 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 path is a file or not.