Member-only story
Checking If a File or Folder Exists in Bash
2 min readAug 26, 2024
In Bash script we can use -f
, -d
, and -e
options to check for file or folder existence.
-f
Operator
The -f
operator checks if a specified path exists and is a regular file. A regular file is a file that contains data, as opposed to a directory or a special file (like a device file).
Usage:
if [ -f "filename.txt" ]; then
echo "filename.txt exists and is a regular file."
else
echo "filename.txt does not exist or is not a regular file."
fi
Explanation:
-f "filename.txt"
: This checks whetherfilename.txt
exists and is a regular file.- If
filename.txt
exists and is a regular file, the condition evaluates totrue
, otherwise evaluates tofalse
.
-d
Operator
The -d
operator checks if a specified path exists and is a directory. This is useful for verifying the presence of directories.
if [ -d "myfolder" ]; then
echo "myfolder exists and is a directory."
else
echo "myfolder does not exist or is not a directory."
fi
Explanation:
-d "myfolder"
: This checks whethermyfolder
exists and is a directory.- If
myfolder
exists and is a directory, the…