Shell Scripting Case Condition


Case Statement:


Case is similar to switch in C or C++. If you need to check a variable for one of many values, you can use case statement. The interpreter checks each case against the value of the expression until a match is found. If no match is found then default condition will be executed and if no default condition mentioned then the case statement exits without performing any action.


Syntax of Case Statement:


case  $variable-name  in
                pattern1)      
                   command1
                   command2
                   ....
                    ;;
                pattern2)
                   command1
                    command2
                    ....
                     ;;           
                *)             
          esac


OR
          case  $variable-name  in
                pattern1|pattern2|pattern3)      
                   command1
                    command2
                    ....
                    ;;
                Pattern4|pattern5|pattern6)
                   command1
                    command2
                    ....
                    ;;
                *)             
          esac

*) is default condition executed for no match is found. But it is not compulsory to include.


Example:

A simple case shell script

#!/bin/bash

echo "Enter a number between 1 and 5 "
read NUM

case $NUM in
        1) echo "one" ;;
        2) echo "two" ;;
        3) echo "three" ;;
        4) echo "four" ;;
        5) echo "five" ;;
        *) echo "NUMBER id not between 1 and 5" ;;
esac


Here we enter a number between 1 and 5 and it stores as NUM variable.  Now case the conditions and prints the number. If the number is not belongs between 1 and 5 then it prints the default condition.






No comments: