Branching on Conditions
Problem
You want to check if you have the right number of arguments and take actions accordingly. You need a branching construct.
Solution
The if statement in bash is similar in appearance to
that in other programming languages:
if [ $# -lt 3 ]
then
printf "%b" "Error. Not enough arguments.\n"
printf "%b" "usage: myscript file1 op file2\n"
exit 1
fior alternatively:
if (( $# < 3 ))
then
printf "%b" "Error. Not enough arguments.\n"
printf "%b" "usage: myscript file1 op file2\n"
exit 1
fiHere’s a full-blown if with an elif (bash-talk for else-if) and an else clause:
if (( $# < 3 ))
then
printf "%b" "Error. Not enough arguments.\n"
printf "%b" "usage: myscript file1 op file2\n"
exit 1
elif (( $# > 3 ))
then
printf "%b" "Error. Too many arguments.\n"
printf "%b" "usage: myscript file1 op file2\n"
exit 2
else
printf "%b" "Argument count correct. Proceeding...\n"
fiYou can even do things like this:
[ $result = 1 ] \
&& { echo "Result is 1; excellent." ; exit 0; } \
|| { echo "Uh-oh, ummm, RUN AWAY! " ; exit 120; }(For a discussion of this last example, see Saving or Grouping Output from Several Commands.)
Discussion
We have two things we need to discuss: the basic structure of the
if statement and how it is that we
have different syntax (parentheses or brackets, operators or options)
for the if expression. The first may
help explain the second. The general form for an if statement, from the manpage for
bash, is:
if list; then list; [ elif list; then list; ] ... [ else list; ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access