13.2.5 Shell conditionals
Each command returns an exit status which can be used for
conditional expressions:
-
Success: 0 (True)
-
Error: 1–255 (False)
Note that the use here of a 0 value to mean "true" differs from the
usual convention in some other areas of computing. Also, `[' is the equivalent
of the test
command, which evaluates its arguments up to `]' as a
conditional expression.
Basic conditional idioms to remember are:
command && if_success_run_this_command_too || true
command || if_not_success_run_this_command_instead
if [ conditional_expression ]; then
if_success_run_this_command
else
if_not_success_run_this_command
fi
Here || true was needed to ensure this shell script will not exit
at this line accidentally when shell is invoked with -e flag.
File comparison operators in the conditional expression are:
-e file True if file exists.
-d file True if file exists and is a directory.
-f file True if file exists and is a regular file.
-w file True if file exists and is writable.
-x file True if file exists and is executable.
file1 -nt file2 True if file1 is newer than file2. (modification)
file1 -ot file2 True if file1 is older than file2. (modification)
file1 -ef file2 True if they are the same device and inode numbers.
String comparison operators in the conditional expression are:
-z str True if the length of str is zero.
-n str True if the length of str is non-zero.
str1 == str2 True if the strings are equal.
str1 = str2 True if the strings are equal.
("=" should be used in place of "==" for strict POSIX compliance)
str1 != str2 True if the strings are not equal.
str1 < str2 True if str1 sorts before str2 (locale dependent).
str1 > str2 True if str1 sorts after str2 (locale dependent).
Arithmetic integer comparison operators in the conditional
expression are -eq, -ne, -lt,
-le, -gt, and -ge.