August 2011
Beginner to intermediate
600 pages
14h 29m
English
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:
$ 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.”
$ 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" ;; ...