bash check if file or directory exists
Quick Answer
# File exists and is a regular file
if [ -f "/path/to/file.txt" ]; then
echo "file exists"
fi
# Directory exists
if [ -d "/path/to/dir" ]; then
echo "directory exists"
fi
# Any file/dir/symlink exists
[ -e "/path/to/thing" ] && echo "exists"
Usage
You need to check if a file or directory exists before reading, writing, or deleting it.
Other causes & fixes
All file test operators
[ -e file ] # exists (file, dir, symlink)
[ -f file ] # exists and is a regular file
[ -d file ] # exists and is a directory
[ -L file ] # exists and is a symbolic link
[ -r file ] # exists and is readable
[ -w file ] # exists and is writable
[ -x file ] # exists and is executable
[ -s file ] # exists and has size > 0
[ -z file ] # string is empty (different — for variables)
File does not exist
if [ ! -f "config.json" ]; then
echo "config.json missing — creating default"
cp config.example.json config.json
fi
Combine conditions
# File exists AND is readable
if [ -f "$file" ] && [ -r "$file" ]; then
cat "$file"
fi
Use [[ ]] for safer tests
# [[ ]] handles empty variables gracefully
file=""
if [[ -f "$file" ]]; then # safe — no word splitting issue
echo "exists"
fi
# [ -f $file ] would fail if $file is empty
Related