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

Get Shell Scripting: Expert Recipes for Linux, Bash, and More 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.