If-then constructs
This block:
if test $# -ne 1 then # Not enough arguments echo -e "Usage:\n$0 output_file" 1>&2 exit 1 fi
executes conditionally the instructions between the then and fi keyword, if and only if the number of arguments passed to the script that contains it is not 1 (test $# -ne 1 )
.
The test command can be used to make different comparisons, arithmetic (-ne, -eq, -lt, ecc
), between strings (-z, ...
) or to test other properties (-f, ...
): it returns 1 if the test is true and 0 if the test is false (see "CONDITIONAL EXPRESSIONS" in the bash man page for more). This makes sense since most of the time people test things for errors, not correct program behavior.
Both the if/then
construct and the test
command can be used indipendently in other situations.
This sets the variable file_present
to 1 if the file "lockfile" is present (and a regular file) in the local directory, or to 0 otherwise:
$ file_present=test -f lockfile $ echo $file_present ...
Another common construct is to use the if/then
block to check if a command exited with an error, since it triggers when the expression between if
and then
is not zero and usually commands exit with non 0 status on error:
$ if ls lockfile then echo "lockfile not present!" else echo "lockfile present" fi