0
0
Bash-scriptingHow-ToBeginner · 3 min read

How to Check if a File Exists in Bash Script

In Bash, you can check if a file exists using the if [ -e filename ] condition. This tests whether the file named filename exists, returning true if it does and false if it doesn't.
📐

Syntax

The basic syntax to check if a file exists in Bash is:

  • if [ -e filename ]: Checks if the file exists (any type of file).
  • then: Starts the block of commands to run if the file exists.
  • else: (Optional) Starts the block if the file does not exist.
  • fi: Ends the if statement.
bash
if [ -e filename ]; then
  echo "File exists."
else
  echo "File does not exist."
fi
💻

Example

This example script checks if a file named example.txt exists in the current directory and prints a message accordingly.

bash
#!/bin/bash

FILE="example.txt"

if [ -e "$FILE" ]; then
  echo "File '$FILE' exists."
else
  echo "File '$FILE' does not exist."
fi
Output
File 'example.txt' does not exist.
⚠️

Common Pitfalls

Common mistakes when checking file existence include:

  • Forgetting to quote the filename variable, which can cause errors if the filename contains spaces.
  • Using -f instead of -e when you want to check for any file type, not just regular files.
  • Confusing the test brackets [ ] with parentheses or forgetting spaces around them.
bash
# Wrong: Missing quotes around variable
FILE=some file.txt
if [ -e $FILE ]; then
  echo "Exists"
fi

# Right: Quotes prevent errors with spaces
FILE="some file.txt"
if [ -e "$FILE" ]; then
  echo "Exists"
fi
📊

Quick Reference

Test OptionMeaning
-e filenameTrue if file exists (any type)
-f filenameTrue if file exists and is a regular file
-d filenameTrue if file exists and is a directory
-r filenameTrue if file is readable
-w filenameTrue if file is writable
-x filenameTrue if file is executable

Key Takeaways

Use [ -e filename ] in Bash to check if a file exists.
Always quote variables like "$FILE" to handle spaces safely.
Use -f if you want to check specifically for regular files.
Remember to include spaces around brackets in the test condition.
Use if ... then ... fi structure to run commands based on file existence.