07. Case statements case, esac

In some cases, a case statement can be more appropriate. For example, when you have a variable and need to execute lines of code depending on its value, the case statement makes for clean code.

Case statements do not execute any test commands and therefore do not use exit codes.

Sample script - Hello!

Here's a script that outputs a greetings depending on which country a user is from.

#!/bin/sh
 
echo "Please select which country you are from: "
 
printf "1: Canada
2: Croatia
3: Czech Republic
4: France
5: Germany
6: Greece
7: Italy
8: Netherlands
9: Poland
10: Sweden
11: United States
"
 
read -p "Country number code: " input
 
case $input in
  1|11) 
    echo 'Hello!'
    ;;
  2) 
    echo 'Bog!'
    ;;
  3) 
    echo 'Ahoj!'
    ;;
  4) 
    echo 'Salut!'
    ;;
  5|8) 
    echo 'Hallo!'
    ;;
  6) 
    echo 'YAH sahs!'
    ;;
  7) 
    echo 'Ciao!'
    ;;
  9) 
    echo 'Czesc!'
    ;;
  10)
    echo 'Hej!'
    ;;
  *)
    echo 'Please enter a valid number.'
    ;;
esac

Notice the use of the | operand. We may also use regular expressions if we are trying to match a string!

We may simplify this script with the select command, which we'll see next.

Sample Script 2 - with Regular Expressions

We can also use case-statements and match input strings with regular expressions!

Let's try to build a script where the user inputs his/her name, and the response changes depending on whether the input starts with a vowel or consonant.

#!/bin/sh
 
printf "What is your first name? "
read first_name
 
case $first_name in
    [aeiouAEIOU]*)
        echo 'Your name starts with a vowel!'
        ;;
    [0-9]*)
        echo 'Strange that your name would start with a number...'
        ;;
    [a-zA-Z]*)
        echo 'Your name starts with a consonant!'
        ;;
    *)
        echo 'Your name starts with some funky punctuation.'
        ;;
esac

Take your Linux skills to the next level!

Command Line Kung Fu

Take your Linux skills to the next level! Try Linux & UNIX

Command Line Kung Fu is packed with dozens of tips and practical real-world examples. You won't find theoretical examples in this book. The examples demonstrate how to solve actual problems. The tactics are easy to find, too. Each chapter covers a specific topic and groups related tips and examples together.

$ Check price
14.9914.99Amazon 4.5 logo(27+ reviews)

More Linux & UNIX resources

Aching back from coding all day?

Acupressure Mat & Pillow

Aching back from coding all day? Try Back Problems

Relieve your stress, back, neck and sciatic pain through 1,782 acupuncture points for immediate neck pain relief. Made for lower, upper and mid chronic back pain treatment, and improves circulation, sleep, digestion and quality of life.

$$ Check price
144.87144.87Amazon 4.5 logo(1,890+ reviews)

More Back Problems resources

Ad