Bash – Check If File Exists

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

In this tutorial, we will go through Bash Script examples to check if file exists covering both the above said expressions.

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

arjun@arjun-VPCEH26EN:/home/tutorialkart$ ls -lt
total 125012
-rw-r--r--  1 root         root                12 Oct  5 09:35 sample.txt
ADVERTISEMENT

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.

#!/bin/bash

# Scenario - File exists
if [ -a /home/tutorialkart/sample.txt ];
then
	echo "sample.txt - File exists."
else
	echo "sample.txt - File does not exist."
fi

# Scenario - File does not exists
if [ -a /home/tutorialkart/dummy.txt ];
then
	echo "dummy.txt - File exists."
else
	echo "dummy.txt - File does not exist."
fi

When the above bash shell script is run in Terminal

arjun@arjun-VPCEH26EN:~/workspace/bash$ ./bash-script-if-file-exists 
sample.txt - File exists.
dummy.txt - File does not exist.

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 ] 

#!/bin/bash

# Scenario - File exists
if [ -e /home/tutorialkart/sample.txt ];
then
	echo "sample.txt - File exists."
else
	echo "sample.txt - File does not exist."
fi

# Scenario - File does not exists
if [ -e /home/tutorialkart/dummy.txt ];
then
	echo "dummy.txt - File exists."
else
	echo "dummy.txt - File does not exist."
fi

When the above bash shell script is run in Terminal

arjun@arjun-VPCEH26EN:~/workspace/bash$ ./bash-script-if-file-exists-2 
sample.txt - File exists.
dummy.txt - File does not exist.

Conclusion

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