d
Amit DhamuSoftware Engineer
 

Switch statement in Bash

2 minute read 00000 views

Here's a really simple example of how to create a switch statement in Bash.

Let's start with a really simple script that will prompt the user to enter their favourite Git hosting provider and store the answer in a variable called SERVICE.

#!/usr/bin/env bash

read -p "Name your favourite Git hosting service: " SERVICE

Next, let's handle the responses of the question using a switch statement.

#!/usr/bin/env bash

read -p "Name your favourite Git hosting service: " SERVICE

case "$SERVICE" in
    'github') echo "GitHub is the best!" ;;
    'gitlab') echo "GitLab is pretty cool too!" ;;
    'bitbucket') echo "Not so keen on Bitbucket!" ;;
    *) echo "Never heard of ${SERVICE}, sorry"
       exit 1
       ;;
esac

As you can see, we handle 3 Git hosting providers and also use * which acts as the default case.

We can mimic fallthrough behaviour and chain certain conditions together too:

#!/usr/bin/env bash

read -p "Name your favourite Git hosting service: " SERVICE

case "$SERVICE" in
    'github' | 'gitlab') echo "Good choice!" ;;
    'bitbucket') echo "Not so keen on Bitbucket!" ;;
    *) echo "Never heard of ${SERVICE}, sorry"
       exit 1
       ;;
esac