Bash Shell: Check File Exists or Not

Bash Shell: Check File Exists or Not

To check if a file exists in a Bash shell, you can use the -e option of the test built-in.

The test built-in is a utility that evaluates an expression and returns a exit status of 0 if the expression is true, or 1 if the expression is false.

To check if a file exists, you can use the -e option followed by the name of the file. For example, to check if the file /etc/hosts exists, you can use the following command:

test -e /etc/hosts
Sourc‮.www:e‬lautturi.com

This will return a exit status of 0 if the file exists, or 1 if the file does not exist.

You can use the $? variable to check the exit status of the test built-in in a script. For example:

if test -e /etc/hosts; then
    # File exists
else
    # File does not exist
fi

This will execute the code in the then clause if the file exists, and the code in the else clause if the file does not exist.

It is important to note that the test built-in only checks for the existence of the file, and does not take into account any other factors that may affect the ability to access the file, such as the permissions or the availability of the file system. To check for other factors that may affect the ability to access the file, you may need to use a different approach.

For more information about the test built-in and its options, you can consult the documentation for the Bash shell.

Created Time:2017-10-27 14:56:35  Author:lautturi