The case Statement

The case statement is used to execute statements depending on a discrete value or a range of values matching the specified variable. In most cases, you can use a case statement instead of an if statement if you have a large number of conditions.

The format of a case statement for pdksh and bash is as follows:

case str in strl | str2)

Statements;; str3|str4)

Statements;;

Statements;;

esac

You can specify a number of discrete valuessuch as strl, str2, and so onfor each condition, or you can specify a value with a wildcard. The last condition should be * (asterisk) and is executed if none of the other conditions are met. For each of the specified conditions, all the associated statements until the double semicolon (;;) are executed.

You can write a script that will echo the name of the month if you provide the month number as a parameter. If you provide a number that isn't between 1 and 12, you will get an error message. The script is as follows:

10) echo "Month is October";;

11) echo "Month is November";;

12) echo "Month is December";; *) echo "Invalid parameter";;

esac

You need to end the statements under each condition with a double semicolon (;;). If you do not, the statements under the next condition will also be executed.

The format for a case statement for tcsh is as follows:

switch (str)

case str1|str2: Statements breaksw case str3|str4: Statements breaksw default:

Statements breaksw endsw

You can specify a number of discrete valuessuch as str1, str2, and so onfor each condition, or you can specify a value with a wildcard. The last condition should be default and is executed if none of the other conditions are met. For each of the specified conditions, all the associated statements until breaksw are executed.

The example that echoes the month when a number is given, shown earlier for pdksh and bash, can be written in tcsh as follows:

set month = 5 switch ( $month )

case

1:

echo

"Month

is

January"

; breaksw

case

2:

echo

"Month

is

February"

; breaksw

case

3

echo

"Month

is

March" ;

breaksw

case

4

echo

"Month

is

April" ;

breaksw

case

5

echo

"Month

is

May" ; breaksw

case

6

echo

"Month

is

June" ;

breaksw

case

7

echo

"Month

is

July" ;

breaksw

case

8:

echo

"Month

is

August"

; breaksw

case

9

echo

"Month

is

September

" ; breaksw

case 10: echo "Month is October" ; breaksw case 11: echo "Month is November" ; breaksw case 12: echo "Month is December" ; breaksw default: echo "Oops! Month is Octember!" ; breaksw endsw

You need to end the statements under each condition with breaksw. If you do not, the statements under the next condition will also be executed.

Was this article helpful?

0 0

Post a comment