File tests

During the execution of a shell script, specific information about a file—such as whether it exists, is writable, is a directory or a file, and so on—may sometimes be required. In bash, the built-in command test performs this function. (There is also a standalone executable version of test available in /usr/bin for non-bash shells.) test has two general forms:

test expression

In this form, test and an expression are explicitly stated.

[ expression ]

In this form, test isn’t mentioned; instead, the expression is enclosed inside brackets.

The expression can be formed to look for such things as empty files, the existence of files, the existence of directories, equality of strings, and others. (See the more complete list with their operators in section, Abbreviated bash command reference. The bash manpage also details all the test options that are available.)

When used in a script’s if or while statement, the brackets ([ and ]) may appear to be grouping the test logically. In reality, [ is simply another form of the test command, which requires the trailing ]. A side effect of this bit of trickery is that the spaces around [ and ] are mandatory, a detail that is sure to get you into trouble eventually.

Get LPI Linux Certification in a Nutshell, 3rd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.