The test Command Syntax
The test command will evaluate the EXPRESSION. Expressions can be built using the following operators and can be built using a combination of operators.
|True if file is a Directory. [[ -d demofile ]]
|True if file Exists. [[ -e demofile ]]
|True if file is a regular File. [[ -f demofile ]]
|True if file is a symbolic Link. [[ -h demofile ]]
|True if file is a symbolic Link. [[ -L demofile ]]
|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:
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
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.