How to Check if File Exists in Bash
• 2 min read
bash file operations file test conditional
Quick Answer: Check if File Exists in Bash
To check if a file exists in Bash, use the -f operator: if [ -f "$file" ]; then. For directories, use -d. These operators work with absolute and relative paths and are safe even if the file doesn’t exist.
Quick Comparison: File Existence Testing Methods
| Operator | Tests For | Usage | Returns True If |
|---|---|---|---|
| -f | Regular file | [ -f "$file" ] | File exists and is regular |
| -d | Directory | [ -d "$dir" ] | Directory exists |
| -e | Any path | [ -e "$path" ] | Any file or directory exists |
| -L | Symbolic link | [ -L "$link" ] | Symbolic link exists |
| -s | Non-empty file | [ -s "$file" ] | File exists and has size > 0 |
Bottom line: Use -f for files, -d for directories, -e for either.
Check if files and directories exist in Bash.
Method 1: Test if File Exists
file="/home/user/file.txt"
if [ -f "$file" ]; then
echo "File exists"
fi
Method 2: Test if Directory Exists
dir="/home/user"
if [ -d "$dir" ]; then
echo "Directory exists"
fi
Method 3: Test if Path Exists
path="/some/path"
if [ -e "$path" ]; then
echo "Path exists (file or directory)"
fi
File Test Operators
| Operator | Test |
|---|---|
-f | Regular file exists |
-d | Directory exists |
-e | Path exists |
-r | File is readable |
-w | File is writable |
-x | File is executable |
-s | File is not empty |
-L | File is symbolic link |
Practical Examples
Check Before Reading
file="$1"
if [ ! -f "$file" ]; then
echo "ERROR: File not found: $file"
exit 1
fi
cat "$file"
Check Before Writing
output_file="output.txt"
if [ -f "$output_file" ]; then
echo "File already exists"
read -p "Overwrite? (y/n) " answer
[ "$answer" != "y" ] && exit 1
fi
echo "Writing data..." > "$output_file"
Check if File is Empty
file="data.txt"
if [ ! -s "$file" ]; then
echo "File is empty"
fi
Check if File is Readable
file="/etc/passwd"
if [ -r "$file" ]; then
echo "File is readable"
fi
Combined Tests
file="script.sh"
if [ -f "$file" ] && [ -x "$file" ]; then
./$file
else
echo "File not found or not executable"
fi
Recommended Pattern
Always quote variables and use -f for files:
if [ -f "$file" ]; then
# File exists
else
echo "File not found"
fi