shell programming - conditionals

created onJanuary 18, 2022

gotchas

In statements like:

if [ ${VAR} -eq 0 ]; then exit 0

there should be a space before and after ‘[’ and ‘]’, otherwise ‘[’ and ‘]’ are not recognized.

types of conditional statements

traditional

traditional shell test command. available on all POSIX shells.

if [ condition ]

alternative

if test -z $VAR

both forms are deprecated. The upgraded (new) version, which follows, should be used instead

upgraded (new) version

upgraded version of test from ksh, also supported by bash and zsh. Supports regex. this is not POSIX.

if [[ condition ]]

again, there should be a space before and after ‘[[’ and ‘]]’, otherwise ‘[[’ and ‘]]’ are not recognized.

arithmetic

ksh extension that is also supported by bash and zsh. returns an exit code of zero (true) if the result of the arithmetic calculation is nonzero. this is not POSIX.

if ((condition))

subshell

runs command in a subshell and acts on exit code

if (command)

command

runs command and acts on exit code

if command

combining tests

deprecated (do not use this):

if [ ! -z $CONF_FILE ] && [ ! -r $CONF_FILE ]; then ...

The better way is to use double brackets. Double brackets are special shell syntax to delimit conditional expressions. Inside double brackets, and are part of conditional expression syntax and do not have the meaning they have in the shell otherwise (taht is, combining commands, where the execution of a command depends on the exit code of the preceeding command).

if [[ ! -z $CONF_FILE && ! -r $CONF_FILE ]]; then ...

Numeric tests can be combined with ‘(’ and ‘)’

if ((($A == 0 || $B != 0) && $C == 0)); then …