Using the test command

The POSIX standard for the shell scripting language specifies a command named test that can be used to test something, and return an exit status to reflect the result.

Which kind of expression to evaluate is specified with the arguments to test. A straightforward and useful test is string equality; are two strings the same? We can try this out with an equals sign between two other shell words:

$ myshell=bash
$ test "$myshell" = 'sh' && printf 'Match!\n'
$ test "$myshell" = 'bash' && printf 'Match!\n'
Match!

Note that the equals sign needs to be a separate word for the test arguments, with spaces before and after, unlike the variable assignment, where we cannot have spaces.

Many other tests are possible:

  • test -e 'myfile' ...

Get Bash Quick Start Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.