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 fi
or alternatively:
if (( $# < 3 )) then printf "%b" "Error. Not enough arguments.\n" printf "%b" "usage: myscript file1 op file2\n" exit 1 fi
Here’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" fi
You 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; ...
Get bash Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.