Case

Let's start with an example this time, as shown in Listing 27-21. Create the script, run it, and then try to explain what it did.

Listing 27-21. Example Script with case #!/bin/bash

# Your personal soccer expert

Enter the name of the country you think will be world champion soccer in 2006. Be aware that the name of the country you enter needs to start with an uppercase letter. EOF

read COUNTRY case $COUNTRY in

Nederland | Holland | Netherlands) echo "Yes, you are an expert in soccer" ;;

Deutschland | Germany | Mannschaft)

echo "No, they are the worst team on earth" ;;

England)

echo "hahahahahahaha, you must be joking" ;;

esac

In case you can't guess, you can use this script to analyze the next world championship games of soccer (of course you can modify it for any major sports event you like). It will first ask the person who runs the script to enter the name of the country that she thinks will be the next champion. This country is put in the $COUNTRY variable. Notice the use of uppercase for this variable; this is a nice way to identify variables easily if your script becomes rather big.

The body of this script consists of the case command. This command evaluates the input the user has entered. The generic construction used to evaluate the input is as follows:

alternative1 | alternative2)

command ;;

So, the first line evaluates everything the user can enter. Notice that most lines offer more than one alternative, which makes it easier to handle typing errors and other situations where the user hasn't typed exactly what you were expecting him to type. Then on separate lines come all the commands you want the script to execute. The example executes just one command, but you can enter 100 lines to execute commands if you like. Finally, the check is closed by using ;;. Don't forget to close all items with a ;;. Otherwise, the script doesn't understand you.

When using case, you should make it a habit to handle "all the other options." We hope your user enters something you expect her to enter. But what if she doesn't? In that case, you probably do want the user to see something. The *) at the end of the script handles this. So in this case, for everything the user enters that isn't specifically mentioned as an option in the script, the script will echo "Huh? Do they play also" to the user.

Was this article helpful?

0 0

Post a comment