[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

16. Conditions

This section describes commands that are primarily useful for their exit status, rather than their output. Thus, they are often used as the condition of shell if statements, or as the last command in a pipeline.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

16.1 false: Do nothing, unsuccessfully

false does nothing except return an exit status of 1, meaning failure. It can be used as a place holder in shell scripts where an unsuccessful command is needed. In most modern shells, false is a built-in command, so when you use `false' in a script, you're probably using the built-in command, not the one documented here.

false honors the `--help' and `--version' options.

This version of false is implemented as a C program, and is thus more secure and faster than a shell script implementation, and may safely be used as a dummy shell for the purpose of disabling accounts.

Note that false (unlike all other programs documented herein) exits unsuccessfully, even when invoked with `--help' or `--version'.

Portable programs should not assume that the exit status of false is 1, as it is greater than 1 on some non-GNU hosts.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

16.2 true: Do nothing, successfully

true does nothing except return an exit status of 0, meaning success. It can be used as a place holder in shell scripts where a successful command is needed, although the shell built-in command : (colon) may do the same thing faster. In most modern shells, true is a built-in command, so when you use `true' in a script, you're probably using the built-in command, not the one documented here.

true honors the `--help' and `--version' options.

Note, however, that it is possible to cause true to exit with nonzero status: with the `--help' or `--version' option, and with standard output already closed or redirected to a file that evokes an I/O error. For example, using a Bourne-compatible shell:

 
$ ./true --version >&-
./true: write error: Bad file number
$ ./true --version > /dev/full
./true: write error: No space left on device

This version of true is implemented as a C program, and is thus more secure and faster than a shell script implementation, and may safely be used as a dummy shell for the purpose of disabling accounts.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

16.3 test: Check file types and compare values

test returns a status of 0 (true) or 1 (false) depending on the evaluation of the conditional expression expr. Each part of the expression must be a separate argument.

test has file status checks, string operators, and numeric comparison operators.

test has an alternate form that uses opening and closing square brackets instead a leading `test'. For example, instead of `test -d /', you can write `[ -d / ]'. The square brackets must be separate arguments; for example, `[-d /]' does not have the desired effect. Since `test expr' and `[ expr ]' have the same meaning, only the former form is discussed below.

Synopses:

 
test expression
test
[ expression ]
[ ]
[ option

Due to shell aliases and built-in test command, using an unadorned test interactively or in a script may get you different functionality than that described here. Invoke it via env (i.e., env test …) to avoid interference from the shell.

If expression is omitted, test returns false. If expression is a single argument, test returns false if the argument is null and true otherwise. The argument can be any string, including strings like `-d', `-1', `--', `--help', and `--version' that most other programs would treat as options. To get help and version information, invoke the commands `[ --help' and `[ --version', without the usual closing brackets. See section Common options.

Exit status:

 
0 if the expression is true,
1 if the expression is false,
2 if an error occurred.

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

16.3.1 File type tests

These options test for particular types of files. (Everything's a file, but not all files are the same!)

`-b file'

True if file exists and is a block special device.

`-c file'

True if file exists and is a character special device.

`-d file'

True if file exists and is a directory.

`-f file'

True if file exists and is a regular file.

`-h file'
`-L file'

True if file exists and is a symbolic link. Unlike all other file-related tests, this test does not dereference file if it is a symbolic link.

`-p file'

True if file exists and is a named pipe.

`-S file'

True if file exists and is a socket.

`-t fd'

True if fd is a file descriptor that is associated with a terminal.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

16.3.2 Access permission tests

These options test for particular access permissions.

`-g file'

True if file exists and has its set-group-ID bit set.

`-k file'

True if file exists and has its sticky bit set.

`-r file'

True if file exists and read permission is granted.

`-u file'

True if file exists and has its set-user-ID bit set.

`-w file'

True if file exists and write permission is granted.

`-x file'

True if file exists and execute permission is granted (or search permission, if it is a directory).

`-O file'

True if file exists and is owned by the current effective user ID.

`-G file'

True if file exists and is owned by the current effective group ID.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

16.3.3 File characteristic tests

These options test other file characteristics.

`-e file'

True if file exists.

`-s file'

True if file exists and has a size greater than zero.

`file1 -nt file2'

True if file1 is newer (according to modification date) than file2, or if file1 exists and file2 does not.

`file1 -ot file2'

True if file1 is older (according to modification date) than file2, or if file2 exists and file1 does not.

`file1 -ef file2'

True if file1 and file2 have the same device and inode numbers, i.e., if they are hard links to each other.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

16.3.4 String tests

These options test string characteristics. You may need to quote string arguments for the shell. For example:

 
test -n "$V"

The quotes here prevent the wrong arguments from being passed to test if `$V' is empty or contains special characters.

`-z string'

True if the length of string is zero.

`-n string'
`string'

True if the length of string is nonzero.

`string1 = string2'

True if the strings are equal.

`string1 != string2'

True if the strings are not equal.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

16.3.5 Numeric tests

Numeric relational operators. The arguments must be entirely numeric (possibly negative), or the special expression -l string, which evaluates to the length of string.

`arg1 -eq arg2'
`arg1 -ne arg2'
`arg1 -lt arg2'
`arg1 -le arg2'
`arg1 -gt arg2'
`arg1 -ge arg2'

These arithmetic binary operators return true if arg1 is equal, not-equal, less-than, less-than-or-equal, greater-than, or greater-than-or-equal than arg2, respectively.

For example:

 
test -1 -gt -2 && echo yes
⇒ yes
test -l abc -gt 1 && echo yes
⇒ yes
test 0x100 -eq 1
error--> test: integer expression expected before -eq

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

16.3.6 Connectives for test

The usual logical connectives.

`! expr'

True if expr is false.

`expr1 -a expr2'

True if both expr1 and expr2 are true.

`expr1 -o expr2'

True if either expr1 or expr2 is true.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

16.4 expr: Evaluate expressions

expr evaluates an expression and writes the result on standard output. Each token of the expression must be a separate argument.

Operands are either integers or strings. Integers consist of one or more decimal digits, with an optional leading `-'. expr converts anything appearing in an operand position to an integer or a string depending on the operation being applied to it.

Strings are not quoted for expr itself, though you may need to quote them to protect characters with special meaning to the shell, e.g., spaces. However, regardless of whether it is quoted, a string operand should not be a parenthesis or any of expr's operators like +, so you cannot safely pass an arbitrary string $str to expr merely by quoting it to the shell. One way to work around this is to use the GNU extension +, (e.g., + "$str" = foo); a more portable way is to use " $str" and to adjust the rest of the expression to take the leading space into account (e.g., " $str" = " foo").

You should not pass a negative integer or a string with leading `-' as expr's first argument, as it might be misinterpreted as an option; this can be avoided by parenthesization. Also, portable scripts should not use a string operand that happens to take the form of an integer; this can be worked around by inserting leading spaces as mentioned above.

Operators may be given as infix symbols or prefix keywords. Parentheses may be used for grouping in the usual manner. You must quote parentheses and many operators to avoid the shell evaluating them, however.

When built with support for the GNU MP library, expr uses arbitrary-precision arithmetic; otherwise, it uses native arithmetic types and may fail due to arithmetic overflow.

The only options are `--help' and `--version'. See section Common options. Options must precede operands.

Exit status:

 
0 if the expression is neither null nor 0,
1 if the expression is null or 0,
2 if the expression is invalid,
3 if an internal error occurred (e.g., arithmetic overflow).

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

16.4.1 String expressions

expr supports pattern matching and other string operators. These have higher precedence than both the numeric and relational operators (in the next sections).

`string : regex'

Perform pattern matching. The arguments are converted to strings and the second is considered to be a (basic, a la GNU grep) regular expression, with a ^ implicitly prepended. The first argument is then matched against this regular expression.

If the match succeeds and regex uses `\(' and `\)', the : expression returns the part of string that matched the subexpression; otherwise, it returns the number of characters matched.

If the match fails, the : operator returns the null string if `\(' and `\)' are used in regex, otherwise 0.

Only the first `\( … \)' pair is relevant to the return value; additional pairs are meaningful only for grouping the regular expression operators.

In the regular expression, \+, \?, and \| are operators which respectively match one or more, zero or one, or separate alternatives. SunOS and other expr's treat these as regular characters. (POSIX allows either behavior.) See (regex)Top section `Regular Expression Library' in Regex, for details of regular expression syntax. Some examples are in Examples of using expr.

`match string regex'

An alternative way to do pattern matching. This is the same as `string : regex'.

`substr string position length'

Returns the substring of string beginning at position with length at most length. If either position or length is negative, zero, or non-numeric, returns the null string.

`index string charset'

Returns the first position in string where the first character in charset was found. If no character in charset is found in string, return 0.

`length string'

Returns the length of string.

`+ token'

Interpret token as a string, even if it is a keyword like match or an operator like /. This makes it possible to test expr length + "$x" or expr + "$x" : '.*/\(.\)' and have it do the right thing even if the value of $x happens to be (for example) / or index. This operator is a GNU extension. Portable shell scripts should use " $token" : ' \(.*\)' instead of + "$token".

To make expr interpret keywords as strings, you must use the quote operator.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

16.4.2 Numeric expressions

expr supports the usual numeric operators, in order of increasing precedence. These numeric operators have lower precedence than the string operators described in the previous section, and higher precedence than the connectives (next section).

`+ -'

Addition and subtraction. Both arguments are converted to integers; an error occurs if this cannot be done.

`* / %'

Multiplication, division, remainder. Both arguments are converted to integers; an error occurs if this cannot be done.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

16.4.3 Relations for expr

expr supports the usual logical connectives and relations. These have lower precedence than the string and numeric operators (previous sections). Here is the list, lowest-precedence operator first.

`|'

Returns its first argument if that is neither null nor zero, otherwise its second argument if it is neither null nor zero, otherwise 0. It does not evaluate its second argument if its first argument is neither null nor zero.

`&'

Return its first argument if neither argument is null or zero, otherwise 0. It does not evaluate its second argument if its first argument is null or zero.

`< <= = == != >= >'

Compare the arguments and return 1 if the relation is true, 0 otherwise. == is a synonym for =. expr first tries to convert both arguments to integers and do a numeric comparison; if either conversion fails, it does a lexicographic comparison using the character collating sequence specified by the LC_COLLATE locale.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

16.4.4 Examples of using expr

Here are a few examples, including quoting for shell metacharacters.

To add 1 to the shell variable foo, in Bourne-compatible shells:

 
foo=`expr $foo + 1`

To print the non-directory part of the file name stored in $fname, which need not contain a /:

 
expr $fname : '.*/\(.*\)' '|' $fname

An example showing that \+ is an operator:

 
expr aaa : 'a\+'
⇒ 3
 
expr abc : 'a\(.\)c'
⇒ b
expr index abcdef cz
⇒ 3
expr index index a
error--> expr: syntax error
expr index + index a
⇒ 0

[ << ] [ >> ]           [Top] [Contents] [Index] [ ? ]

This document was generated on January, 20 2010 using texi2html 1.76.