In this tutorial we look at Bash case based conditional statements.

Yet another set of languages (like C#, C++, Java and JavaScript) call this aswitchorswitch/casestatement.

All these have similar meanings and operations.

synology nas

Let’s build our firstcase .. esacstatement using a simple script.

“;;

  1. echo “Option was 2!

Note that there are two;end-of-statement terminators at the end of each line.

Four hard drivers sticking out of a rack-mount server that’s being used as a NAS.

We can see how we have defined code for both the cases where1and2are passed to the script, respectively.

However, what happens when we pass something else?

In that case, we want to jump to ourotherclause, indicated by a universal*idiom.

The main page of the Homepage homelab dashboard with services running on it.

We see how we pass1or2to the script, the corresponding correct action is taken;Option was 1/2!.

What would happen if we passed no option to our script?

Note that only a single terminating;was used in this script.

Article image

echo “Or, option was 3!

Note how everything works well and the inputs1and3are correctly parsed.

This again works flawlessly.

A simple case .. esac statement in Bash

Wrapping up

In this tutorial, we looked at practical examples of Bash basedcase .. esacstatements.

We also saw where case statements are a better choice then more traditionalif .. then .. fibased statements.

Not passing a variable to our test script also works due to the * clause in our case .. esac statement

Incorrect code block termination in a Bash case..esac statement

An alternative to a case..esac statement using an if..then..elif..else..fi statement

A more complex case .. esac statement in Bash with additional selectors