Bash by Example: Check File Exists
Verifying if a file exists before performing operations using test operators and conditional expressions, understanding the -f flag for regular files versus -e for any filesystem entity, implementing file validation in scripts to prevent errors, using file existence checks in error handling logic, and combining with other file attribute tests.
Code
#!/bin/bash
filename="config.conf"
# Check if file exists AND is a regular file
if [ -f "$filename" ]; then
echo "$filename exists."
else
echo "$filename does not exist."
fi
# Check if file does NOT exist
if [ ! -f "$filename" ]; then
echo "Creating default config..."
touch "$filename"
fi
# Check if file exists (any type: file, dir, link...)
if [ -e "$filename" ]; then
echo "Path exists."
fi
rm "$filename"Explanation
Before reading from or writing to a file, it is best practice to check if it exists. The -f operator checks if the path exists and is a regular file (not a directory or device).
To check for the absence of a file, use the negation operator ! before the test flag: [ ! -f file ]. This is commonly used to create default configuration files or initialize data if it's missing.
The -e operator is broader; it returns true if the path exists regardless of what it is (directory, symlink, etc.). Use -f when you specifically need a file.
Code Breakdown
[ -f ... ] is the standard check for files. Always quote the filename to handle spaces correctly.! operator negates the test. "If NOT file exists".
