-f vs -d vs -e in Bash: Key Differences and Usage
-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.
| Operator | Checks For | Returns True If | Common Use Case |
|---|---|---|---|
| -f | Regular file | File exists and is a regular file (not directory or special file) | Check if a normal file exists before reading or writing |
| -d | Directory | File exists and is a directory | Check if a directory exists before accessing or creating files inside |
| -e | Any file system object | File or directory exists regardless of type | General 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:
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
-d Equivalent
Here is a Bash script using -d to check if a directory exists:
dirname="myfolder" if [ -d "$dirname" ]; then echo "$dirname is a directory." else echo "$dirname is not a directory or does not exist." fi
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
-f to check for regular files only.-d to check for directories only.-e to check if any file system object exists.