Наши партнеры

7.1. Test Constructs

An if/then construct tests whether the
exit status of a list
of commands is 0 (since 0 means
"success" by UNIX convention), and if so, executes
one or more commands.

There exists a dedicated command called [ (left bracket
special character). It is a synonym for test,
and a builtin for efficiency
reasons. This command considers its arguments as comparison
expressions or file tests and returns an exit status corresponding
to the result of the comparison (0 for true, 1 for false).

With version 2.02, Bash introduced the [[ ... ]]extended
test command, which performs comparisons
in a manner more familiar to programmers from other
languages. Note that [[ is a keyword, not a command.

Bash sees [[ $a -lt $b ]] as a
single element, which returns an exit status.

When if and then
are on same line in a condition test, a semicolon must
terminate the if statement. Both
if and then
are keywords. Keywords (or
commands) begin statements, and before a new statement on the
same line begins, the old one must terminate.

if [ -x "$filename" ]; then

Else if and elif

elif

elif is a contraction
for else if. The effect is to nest an
inner if/then construct within an outer
one.

The if test condition-true construct is the
exact equivalent of if [ condition-true ].
As it happens, the left bracket, [ , is a
token[1]
which invokes the test command. The closing
right bracket, ] , in an if/test should not
therefore be strictly necessary, however newer versions of Bash
require it.

The test command is a Bash builtin which tests file
types and compares strings. Therefore, in a Bash script,
test does not call
the external /usr/bin/test binary,
which is part of the sh-utils
package. Likewise, [ does not call
/usr/bin/[, which is linked to
/usr/bin/test.

bash$ type testtest is a shell builtinbash$ type '['[ is a shell builtinbash$ type '[['[[ is a shell keywordbash$ type ']]']] is a shell keywordbash$ type ']'bash: type: ]: not found

If, for some reason, you wish to use
/usr/bin/test in a Bash script,
then specify it by full pathname.

Using the [[ ... ]] test construct,
rather than [ ... ] can prevent many
logic errors in scripts. For example, the &&,
||, <, and >
operators work within a [[ ]] test, despite
giving an error within a [ ] construct.

The (( ))
construct expands and evaluates an arithmetic
expression. If the expression evaluates as zero, it returns
an exit status of
1, or "false". A non-zero
expression returns an exit status of 0,
or "true". This is in marked contrast to using
the test and [ ] constructs
previously discussed.