Bash – Check If File Exists – if [-e FILE]

Bash – Check If File Exists

Bash Script to Check If File Exists – To check if file exists in bash scripting, we shall use [ -a FILE ] and [ -e FILE ]  expressions with bash if statement. [-e FILE] is preferred as [-a FILE] is depreciated. Bash Script Examples are provided to check if file exists.

Examples :

  • Example 1 – Using [ -a FILE ] (Depreciated method to check in bash if file exists.)
  • Example 2 – Using [ -e FILE ] (Preferred method to check in bash if file exists.)

We shall use a sample.txt file for this example

 

Example 1 – Using [ -a FILE ] expression with if statement

For this example, there is a file /home/tutorialkart/sample.txt present and /home/tutorialkart/dummy.txt not present. We shall demonstrate the result with the help of following example.

When the above bash shell script is run in Terminal

 

Example 2 – Using [ -e FILE ] expression with if statement

We shall use the same files as in Example 1, but with a new expression [ -e FILE ] 

When the above bash shell script is run in Terminal

 

Conclusion :

In this Bash TutorialBash – Check If File Exists, we have learnt to check if a specified file exists using [-e FILE] condition.