"test" command in Linux with examples

Using the test Command

The test command is used for testing conditions. This command is very useful in shell scripts. The test command can be used to verify many conditions, including:

  • Variable contents
  • File access permissions
  • File types

The test command can be written as test expression or by using the[expression] special notation. The test command does not return any output. If the condition being tested is true, the exit status of the test command is set to 0. If the condition being tested is false, the exit status is set to 1.

Examples of the test command include the following:

1. Test if the value of the LOGNAME variable is user1.

$ echo $LOGNAME
user1
$ test "$LOGNAME" = "user1"
$ echo $?
0

2. Test if the value of the LOGNAME variable is user1 by using the [ expression ] notation.

$ echo $LOGNAME
user1
$ [ "$LOGNAME" = "user1" ]
$ echo $?
0

3. Test if the user has read permissions on the /etc/group file.

$ ls -l /etc/group
-rw-r--r--   1 root sys  290 Sep 13 15:14 /etc/group
$ test -r /etc/group
$ echo $?
0

4. Test if the user has read permissions on the /etc/group file by using the [ expression ] notation.

$ ls -l /etc/group
-rw-r--r--   1 root sys  290 Sep 13 15:14 /etc/group
$ [ -r /etc/group ]
$ echo $?
0

5. Determine if /etc is a directory.

$ ls -ld /etc
drwxr-xr-x  53 root     sys         3584 Sep 18 11:48 /etc
$ test -d /etc
$ echo $?
0

6. Determine if /etc is a directory using the [expression] notation.

$ [ -d /etc ]
$ echo $?
0

7. Compare the result against a known file.

$ test -d /etc/group
$ echo $?
1

8. Compare against a known file using the [expression] notation.

$ [ -d /etc/group ]
$ echo $?
1