Conditional Statement (Case) in Shell Script

Case statement in Shell Script is similar to switch statement in C. It can be used to test simple values like integers and characters.

Case statement is not a loop, it doesn’t execute a block of code for n number of times. Instead, bash shell checks the condition, and controls the flow of the program.

In this article let us review the bash case command with 5 practical examples.

The case construct in bash shell allows us to test strings against patterns that can contain wild card characters. Bash case statement is the simplest form of the bash if-then-else statement.

Syntax of bash case statement.

case  $variable-name  in
                pattern1)       
     		    command1
                    ...
                    ....
                    commandN
                    ;;
                pattern2)
     		    command1
                    ...
                    ....
                    commandN
                    ;;            
                patternN)       
     		    command1
                    ...
                    ....
                    commandN
                    ;;
                *)              
          esac
Following are the key points of bash case statements:
  • Case statement first expands the expression and tries to match it against each pattern.
  • When a match is found all of the associated statements until the double semicolon (;;) are executed.
  • After the first match, case terminates with the exit status of the last command that was executed.
  • If there is no match, exit status of case is zero.

Few Examples

1. Check the Fruit Name.

FRUIT="kiwi"

case "$FRUIT" in
   "apple") echo "Apple pie is quite tasty." 
   ;;
   "banana") echo "I like banana nut bread." 
   ;;
   "kiwi") echo "New Zealand is famous for kiwi." 
   ;;
esac

2. Check the Entered Number.

case $Number in
   0) echo "It is ZERO." 
   ;;
   1) echo "It is ONE." 
   ;;
   *) echo "It is Not ZERO nor ONE." 
   ;;
esac
 

Leave a Reply

Your email address will not be published.