Chapter 25. List Constructs

The "and list" and "or list" constructs provide a means of processing a number of commands consecutively. These can effectively replace complex nested if/then or even case statements.

Chaining together commands

and list

command-1 && command-2 && command-3 && ... command-n
Each command executes in turn provided that the previous command has given a return value of true (zero). At the first false (non-zero) return, the command chain terminates (the first command returning false is the last one to execute).

Of course, an and list can also set variables to a default value.
arg1=$@       # Set $arg1 to command line arguments, if any.

[ -z "$arg1" ] && arg1=DEFAULT
              # Set to DEFAULT if not specified on command line.

or list

command-1 || command-2 || command-3 || ... command-n
Each command executes in turn for as long as the previous command returns false. At the first true return, the command chain terminates (the first command returning true is the last one to execute). This is obviously the inverse of the "and list".

Caution

If the first command in an "or list" returns true, it will execute.

Important

The exit status of an and list or an or list is the exit status of the last command executed.

Clever combinations of "and" and "or" lists are possible, but the logic may easily become convoluted and require extensive debugging.
false && true || echo false    # false

# Same result as
( false && true ) || echo false     # false
# But *not*
false && ( true || echo false )     # (nothing echoed)

# Note left-to-right grouping and evaluation of statements,
# since the logic operators "&&" and "||" have equal precedence.

# It's best to avoid such complexities, unless you know what you're doing.

# Thanks, S.C.

See Example A-8 for an illustration of using an and / or list to test variables.