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.

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
    echo 'Hello!'
    echo 'Bog!'
    echo 'Ahoj!'
    echo 'Salut!'
    echo 'Hallo!'
    echo 'YAH sahs!'
    echo 'Ciao!'
    echo 'Czesc!'
    echo 'Hej!'
    echo 'Please enter a valid number.'

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.

printf "What is your first name? "
read first_name
case $first_name in
        echo 'Your name starts with a vowel!'
        echo 'Strange that your name would start with a number...'
        echo 'Your name starts with a consonant!'
        echo 'Your name starts with some funky punctuation.'

Take your Linux skills to the next level!

How Linux Works

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

In this completely revised second edition of the perennial best seller How Linux Works, author Brian Ward makes the concepts behind Linux internals accessible to anyone curious about the inner workings of the operating system. Inside, you'll find the kind of knowledge that normally comes from years of experience doing things the hard way.

$ Check price
39.9539.95Amazon 5 logo(114+ reviews)

More Linux & UNIX resources

Aching back from coding all day?

Inversion Therapy Table

Aching back from coding all day? Try Back Problems

Stretch out your back and relieve your back muscles with inversion therapy. This device counteracts the forces of gravity on the body by decompressing and elongating the spine. By using this product just ten minutes a day, you can be well on your way to improved circulation and posture while relieving muscle aches, back pain and stress.

$$ Check price
119.98119.98Amazon 4.5 logo(1,700+ reviews)

More Back Problems resources