Bash Case Statement with examples

This article will introduce Case statement in Bash. It is similar to Switch-Case in other languages.

1. Syntax

The syntax of Case statement is as follows.

  • If there is a pattern_X) that matches the expression, the statements in that block will be executed
  • You can use the | operator to apply multiple conditions to one pattern, like pattern_3|pattern_4)
  • Items that do not match the condition can be handled in *)
case expression in  
    pattern_1)  
        statements  
        ;;  
    pattern_2)  
        statements  
        ;;  
    pattern_3|pattern_4|pattern_5)  
        statements  
        ;;  
    *)  
        statements  
        ;;
esac

2. Example of Case statement

You can use the Case statement to perform the conditional statement corresponding to the var.

#!/bin/bash

var=1
case $var in
  1)
    echo "Apple"
    ;;
  2)
    echo "Grape"
    ;;
  3)
    echo "Kiwi"
    ;;
esac

Output:

$ bash example.sh
Apple

3. Case statement with User input

In this example, it takes in User Input and prints out a specific string. If there is no matching pattern, it is handled from *).

#!/bin/bash

read -p "Yes or No? : " Answer

case $Answer in
  Yes|yes|y|Y)
    echo "You typed 'Yes'"
    ;;  
  No|no|N|n)  
    echo "You typed 'No'"
    ;;
  *)
    echo "Invalid answer"
esac

Output:

$ bash example.sh
Yes or No? : Y
You typed 'Yes'

$ bash example.sh
Yes or No? : No
You typed 'No'

$ bash example.sh
Yes or No? : NO  
Invalid answer

4. Case statement with Regex

This is an example of using regular expressions.

#!/bin/bash

read -p "Type something : " Answer

case $Answer in
  a?)
    echo "a? pattern"
    ;;  
  b*)  
    echo "b* pattern"
    ;;
  c[def])
    echo "cd | ce | cf"
    ;;
  *)
    echo "Invalid answer"
    ;;
esac
  • ?: It means one character. The pattern a? matches when it starts with an 'a' and is followed by one character.
  • *: It means one or more of any characters. The pattern a* matches when there is one or more characters after an 'a'.
  • [abc] : It means one of the characters a or b or c. The pattern a[bc] is judged to match ab and ac.

This is the result of above example.

$ bash example.sh
Type something : a
Invalid answer

$ bash example.sh
Type something : a1
a? pattern

$ bash example.sh
Type something : a22
Invalid answer

$ bash example.sh
Type something : bbaabbaa
b* pattern

$ bash example.sh
Type something : cd
cd | ce | cf

$ bash example.sh
Type something : cdd
Invalid answer
codechachaCopyright ©2019 codechacha