O'Reilly logo

Shell Scripting: Expert Recipes for Linux, Bash, and More by Steve Parker

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

Case

case provides a much cleaner, easier-to-write, and far more readable alternative to the if/then/else construct, particularly when there are a lot of possible values to test for. With case, you list the values you want to identify and act upon, and then provide a block of code for each one. A basic case block looks like this:

download.eps
cat fruit.sh
#!/bin/bash
read -p "What is your favorite fruit?: " fruit
case $fruit in
  orange) echo "The $fruit is orange" ;;
  banana) echo "The $fruit is yellow" ;;
  pear) echo "The $fruit is green" ;;
  *) echo "I don't know what color a $fruit is" ;;
esac
$ ./fruit.sh 
What is your favorite fruit?: banana
The banana is yellow
$ ./fruit.sh 
What is your favorite fruit?: apple
I don't know what color a apple is
$ 

fruit.sh

This displays the color of various fruits, and catches any others in the * handler. To go back to the use of elif to deal with multiple different unames, you can make this even shorter and easier to understand using case. Notice that this is not intelligent enough to correct its grammar when displaying the text “a apple.”

download.eps
cat uname-case.sh #!/bin/bash OS='uname -s' case "$OS" in   FreeBSD) echo "This is FreeBSD" ;;   CYGWIN_NT-5.1) echo "This is Cygwin" ;;   SunOS) echo "This is Solaris" ;;   Darwin) echo "This is Mac OSX" ;; ...

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