dreamsys software

UNIX & Linux Shell Scripting Tutorial

Cases

Many programming languages and scripting languages have the concept of a case or select statement. This is generally used as a shortcut for writing if/else statements. The case statement is always preferred when there are many items to select from instead of using a large if/elif/else statement. It is usually used to implement menus in a script. The case statement is terminated with esac (case backwards). Here is a simple example of using a case statement:

#!/bin/sh

echo "Enter a number between 1 and 10. "
read NUM

case $NUM in
	1) echo "one" ;;
	2) echo "two" ;;
	3) echo "three" ;;
	4) echo "four" ;;
	5) echo "five" ;;
	6) echo "six" ;;
	7) echo "seven" ;;
	8) echo "eight" ;;
	9) echo "nine" ;;
	10) echo "ten" ;;
	*) echo "INVALID NUMBER!" ;;
esac

The 1, 2, etc. are the different values that could possibly be contained in the given variable ($NUM). The * indicates how you will handle any value that is unexpected. This application will keep track of how many people want chicken and how many want steak for a wedding reception. The user will also have an option to exit.

#!/bin/sh
# Wedding guest meals

# These variables hold the counters.
NUM_CHICKEN=0
NUM_STEAK=0
ERR_MSG=""

# This will clear the screen before displaying the menu.
clear

while :
do
	# If error exists, display it
	if [ "$ERR_MSG" != "" ]; then
		echo "Error: $ERR_MSG"
		echo ""
	fi

	# Write out the menu options...
	echo "Chicken: $NUM_CHICKEN"
	echo "Steak: $NUM_STEAK"
	echo ""
	echo "Select an option:"
	echo " * 1: Chicken"
	echo " * 2: Steak"
	echo " * 3: Exit"

	# Clear the error message
	ERR_MSG=""

	# Read the user input
	read SEL

	case $SEL in
		1) NUM_CHICKEN=`expr $NUM_CHICKEN + 1` ;;
		2) NUM_STEAK=`expr $NUM_STEAK + 1` ;;
		3) echo "Bye!"; exit ;;
		*) ERR_MSG="Please enter a valid option!"
	esac

	# This will clear the screen so we can redisplay the menu.
	clear
done

Since we clear the screen before displaying the menu each time, we must keep track of any error messages and display them if an error occurs before we draw the menu and after we clear the screen. The screen is cleared by using the unix clear command. Notice in option 3 that you can separate unix commands on a single line by using the ; (semicolon).


Prev (Looping) | Next (Functions)


Blog Entries
Blob Entry 1
Blob Entry 2
Blob Entry 3
Blob Entry 4
Blob Entry 5
Blob Entry 6