How To Check If A File Exist In Bash?

Linux bash provides a lot of built-in commands in order to execute different tasks. There are different commands and tools which can be used to check if a file exists. The file existence can be checked with different commands like test . Also, these bash methods can be used inside bash scripts in order to check file existence and execute code accordingly.

Check If File Exist with test

Bash provides the test statement in order to test the existence of the specified file or directory. We can use the test statement in order to test if the specified file exists. The test statement is generally used with a if statement in order to execute commands according to the file existence. In the following example, we check the file /etc/hosts file.

if test -f "/etc/hosts"; then
   echo "etc/hosts exists."
fi

Alternatively, we can use variables in order to set the file name and path and then check the file’s existence via this variable. In the following example, we use the variable FILE to set the file path and check with the test statement.

FILE = "/etc/hosts";

if test -f "$FILE"; then
   echo "etc/hosts exists."
fi

Check If File Exist with if Condition

Even the test statement provides the ability to check a file exitance there are alternatives. The if statement can be used to check file existence by using the -f option and [] signs. The [ -f /etc/hosts ] is used to check if the file /etc/hosts exist.

if [ -f "/etc/hosts" ]; then
   echo "etc/hosts exists."
fi

Alternatively, bash variables can be used to specify the file path and name.

FILE=/etc/hosts

if [ -f "$FILE" ]; then
   echo "etc/hosts exists."
fi

Check If Multiple Files Exist

The if statement can be used to check if multiple files exist at the same time. If all of the checked files exist the if statement body will be executed. If at least one of the check files does not exist the if statement will be evaluated as false.

if [ -f "/etc/hosts" -a -f "/etc/passwd" ]; then
   echo "/etc/hosts and /etc/passwd exists."
fi

Check If Directory Exist

The bash also provides an exitance check mechanism for directories or folders. The -d option is used to check a directory existence like below.

if [ -f "/etc" ]; then
   echo "/etc exists."
fi

Leave a Comment