[Next] [Previous] [Up] [Top] [Contents]

9.9 Control Commands

9.9.6 test

Conditional statements are evaluated for true or false values. This is done with the test, or its equivalent, the [] operators. It the condition evaluates to true, a zero (TRUE) exit status is set, otherwise a non-zero (FALSE) exit status is set. If there are no arguments a non-zero exit status is set. The operators used by the Bourne shell conditional statements are given below.

For filenames the options to test are given with the syntax:

-option filename

The options available for the test operator for files include:

-r true if it exists and is readable

-w true if it exists and is writable

-x true if it exists and is executable

-f true if it exists and is a regular file (or for csh, exists and is not a directory)

-d true if it exists and is a directory

-h or -L true if it exists and is a symbolic link

-c true if it exists and is a character special file (i.e. the special device is accessed one character at a time)

-b true if it exists and is a block special file (i.e. the device is accessed in blocks of data)

-p true if it exists and is a named pipe (fifo)

-u true if it exists and is setuid (i.e. has the set-user-id bit set, s or S in the third bit)

-g true if it exists and is setgid (i.e. has the set-group-id bit set, s or S in the sixth bit)

-k true if it exists and the sticky bit is set (a t in bit 9)

-s true if it exists and is greater than zero in size

There is a test for file descriptors:

-t [file_descriptor] true if the open file descriptor (default is 1, stdin) is associated with a terminal

There are tests for strings:

-z string true if the string length is zero

-n string true if the string length is non-zero

string1 = string2 true if string1 is identical to string2

string1 != string2 true if string1 is non identical to string2

string true if string is not NULL

There are integer comparisons:

n1 -eq n2 true if integers n1 and n2 are equal

n1 -ne n2 true if integers n1 and n2 are not equal

n1 -gt n2 true if integer n1 is greater than integer n2

n1 -ge n2 true if integer n1 is greater than or equal to integer n2

n1 -lt n2 true if integer n1 is less than integer n2

n1 -le n2 true if integer n1 is less than or equal to integer n2

The following logical operators are also available:

! negation (unary)

-a and (binary)

-o or (binary)

() expressions within the () are grouped together. You may need to quote the () to prevent the shell from interpreting them.


Introduction to Unix - 14 AUG 1996
[Next] [Previous] [Up] [Top] [Contents]