Case And Wildcards

The case statement matches an expression with multiple alternatives. This is similar to the switch-case construct to of C/C++. The general from of the case construct is:

case "$variable" in
            condition 1) commands;;
            condition 2) commands;;
            -----------------------
            -----------------------
            -----------------------
condition n) commands
esac

Note : That each alternative ends with a) and each condition block with two semicolons (;;). The last condition block need not be terminated with ;;. The case block ends with esac (case spelled backwards).

Example of case statement:

#stored in file case.sh
echo "Press any key"
read key
echo "You have typed a"
case "$key" in
            [a-z]) echo "lowercase letter";;
            [A-Z]) echo "uppercase letter";;
            [0-9]) echo "digit";;
            *) echo "punctuation, space or any other key"
esac

Output:



This shell script matches the character typed by the user with the specified alternatives and performs the actions (commands) corresponding to the matched argument.


Note: The * has got double meaning if used int the case construct. When used as part of a pattern it functions as a wild-card and when used as the last option it matches a value not matched by the previous options. If no match is found, the command following this option (*) is executed.

#stored in file case1.sh
read i
echo "$i is "
case $i in
            [1-9]*) echo "a positive value";;
            [-]*) echo "a negative value";;
            [0]) echo "zero";;
            *) echo "not a number"
esac

Output:

1 comment:

  1. I see your blog needs some unique content. Writing manually is time consuming, there is
    tool for this task. Just search in gogle for; Fejlando's tips

    ReplyDelete