O'Reilly logo

bash Cookbook by Cameron Newham, JP Vossen, Carl Albing

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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,"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; ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required