Skip to Content
Shell Scripting: Expert Recipes for Linux, Bash, and More
book

Shell Scripting: Expert Recipes for Linux, Bash, and More

by Steve Parker
August 2011
Beginner to intermediate
600 pages
14h 29m
English
Wrox
Content preview from Shell Scripting: Expert Recipes for Linux, Bash, and More

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" ;; ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Linux Command Line and Shell Scripting Techniques

Linux Command Line and Shell Scripting Techniques

Vedran Dakic, Jasmin Redzepagic
Linux Shell Scripting Cookbook - Third Edition

Linux Shell Scripting Cookbook - Third Edition

Clif Flynt, Sarath Lakshman, Shantanu Tushar

Publisher Resources

ISBN: 9781118166321Purchase bookDownloads