You can check whether a file or directory exists on a Linux system using the test command in bash. See our examples below to find out how.
The test Command Syntax
test EXPRESSION
The test command will evaluate the EXPRESSION. Expressions can be built using the following operators and can be built using a combination of operators.
-d file | True if file is a Directory. [[ -d demofile ]] |
-e file | True if file Exists. [[ -e demofile ]] |
-f file | True if file is a regular File. [[ -f demofile ]] |
-h file | True if file is a symbolic Link. [[ -h demofile ]] |
-L file | True if file is a symbolic Link. [[ -L demofile ]] |
-s file | True if file has a Size greater than zero. [[ -s demofile ]] |
The test command can also be used for other types of comparisons, like comparing file dates, types, and permissions, and comparing strings and numbers – to view the user manual for the test command run the following in the Linux shell:
man test
You’ve probably noticed those [[]] (square brackets) – square brackets can be used in place of the find command – but we’ll avoid doing that to keep things easy to understand.
The test Command Examples
You can quickly check if a file or directory exists by using the && operator on the Linux shell, which will only run if the test command exits with a status of TRUE:
test -e /path/to/myfile && echo "File or directory exists."
Using the test Command with an if Statement
You can build scripts with conditional logic using if..else statements and find:
if test -f path/to/myfile; then echo "File exists and is a regular file." elif test -d path/to/myfile; then echo "File exists and is a directory." else echo "File does not exist." fi
Conclusion
When writing to a user’s file system, it’s never wise to just modify or create a file without checking what was there first – you could be destroying valuable data and get yourself into trouble.
Good scripts will check for a file’s presence first and ask the user what action should be taken – and the above method can be built on to do just that.
For more tutorials on navigating with the Linux shell, click here!