0
0
Bash-scriptingComparisonBeginner · 3 min read

-f vs -d vs -e in Bash: Key Differences and Usage

In Bash, -f checks if a file exists and is a regular file, -d checks if a directory exists, and -e checks if a file or directory exists regardless of type. Use -f for regular files, -d for directories, and -e for any file system object.
⚖️

Quick Comparison

Here is a quick table summarizing the main differences between -f, -d, and -e in Bash.

OperatorChecks ForReturns True IfCommon Use Case
-fRegular fileFile exists and is a regular file (not directory or special file)Check if a normal file exists before reading or writing
-dDirectoryFile exists and is a directoryCheck if a directory exists before accessing or creating files inside
-eAny file system objectFile or directory exists regardless of typeGeneral existence check for any file or directory
⚖️

Key Differences

The -f operator tests specifically for regular files. This means it returns true only if the path exists and is a normal file, not a directory or device file. Note that it returns false for symbolic links unless the link points to a regular file.

The -d operator is used to check if a path exists and is a directory. It returns false for regular files or other types.

The -e operator is the most general. It returns true if the path exists, no matter what type it is—file, directory, symbolic link, or special device. This makes it useful when you only care about existence, not type.

⚖️

Code Comparison

Here is a Bash script using -f to check if a regular file exists:

bash
filename="example.txt"

if [ -f "$filename" ]; then
  echo "$filename is a regular file."
else
  echo "$filename is not a regular file or does not exist."
fi
Output
example.txt is a regular file.
↔️

-d Equivalent

Here is a Bash script using -d to check if a directory exists:

bash
dirname="myfolder"

if [ -d "$dirname" ]; then
  echo "$dirname is a directory."
else
  echo "$dirname is not a directory or does not exist."
fi
Output
myfolder is a directory.
🎯

When to Use Which

Choose -f when you need to confirm a regular file exists before reading or writing it. Choose -d when you want to verify a directory exists before creating or accessing files inside it. Choose -e when you only need to check if a path exists regardless of its type, such as before deciding to create or skip it.

âś…

Key Takeaways

Use -f to check for regular files only.
Use -d to check for directories only.
Use -e to check if any file system object exists.
Choose the operator based on whether you care about file type or just existence.
These operators help avoid errors by confirming file or directory presence before actions.