Sunday 13 August 2017

Bash Testing an Expression

Cited from the Book "Pro Bash Programming"

Expressions are deemed to be true or false by the test command or one of two nonstandard shell reserved words, [[ and ((. The test command compares strings, integers, and various file attributes; (( tests arithmetic expressions, and [[ ... ]] does the same as test with the additional feature of comparing regular expressions.

The -z and -n operators return successfully if their arguments are empty or nonempty.

$ [ -z "" ]
$ echo $?
0
$ test -n ""
$ echo $?
1
The greater-than and less-than symbols are used in bash to compare the lexical positions of strings and must be escaped to prevent them from being interpreted as redirection operators:

$ str1=abc
$ str2=def
$ test "$str1" \< "$str2"
$ echo $?
0
$ test "$str1" \> "$str2"
$ echo $?
1

For "test" command, "-a" (logical AND) and -o (logical OR) operators can be used to combine expression conditions.

Like test, [[ ... ]] evaluates an expression. Unlike test, it is not a built-in command. It is part of the shell grammar and not subject to the same parsing as a built-in command. Parameters are expanded, but word splitting and file name expansion are not performed on words between [[ and ]].

A list is a sequence of one or more commands separated by semicolons, ampersands, control operators, or newlines. A list may be used as the condition in a while or until loop or as the body of any loop. The exit code of a list is the exit code of the last command in the list.

No comments:

Post a Comment