Skip to main content

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

OperatorTests ForUsageReturns True If
-fRegular file[ -f "$file" ]File exists and is regular
-dDirectory[ -d "$dir" ]Directory exists
-eAny path[ -e "$path" ]Any file or directory exists
-LSymbolic link[ -L "$link" ]Symbolic link exists
-sNon-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

OperatorTest
-fRegular file exists
-dDirectory exists
-ePath exists
-rFile is readable
-wFile is writable
-xFile is executable
-sFile is not empty
-LFile 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

Always quote variables and use -f for files:

if [ -f "$file" ]; then
  # File exists
else
  echo "File not found"
fi