test is a Bash builtin which test file types and compare values. Is one of the most basic tools any Linux user should know.

It has two main structures:

test EXPRESSION
# This will sound familiar if you have used conditionals
[ EXPRESSION ]

The result of the test returns as an exit status of 0 (for ‘true’) or 1 (for ‘false’).

Check Bash syntax: Operators to get info about how to compare strings or integers. You can also test file types (e.g.: test if a path is a file, a directory, a symbolic link, etc.). These are some of the expressions to test file types (check test man page for more):

  • -e <file>: test if file exists.
  • -f <file>: test if file exists and is a regular file.
  • -d <file>: test if file exists and is a directory.
  • -h <file>: test if file exists and is a symbolic link (same as -L <file>).
  • -r <file>: test if file exists and read permission is granted (for the user that runs the command).
  • -w <file>: test if file exists and write permission is granted.
  • -x <file>: test if file exists and execute permission is granted.
  • <file> -nt <file2>: test if file is newer than file2.
  • <file> -ot <file2>: test if file is older than file2.

This is an example of how to use test (I am going to use echo $? to return the exit status of test):

# some_file.txt exists
$ test -e some_file.txt
$ echo $?
0

If you have any suggestion, feel free to contact me via social media or email.