How To Use Case Statements In Bash Scripts

Case statements are useful for a variety of things including adding a help dialog/message to your script. Below are a few different examples of using a case statement.

Defining Arguments

For our first example we will use a case statement to create a help dialog. This is useful if add other options to your script or if variables can be set from the command line and you need a reminder.

Create Help Message In Bash

Checking Variable Values

In this example I will show you how to use it to check if a variable is a certain expected value. I will also show you how to catch a variable that has an unexpected or invalid value.

Case Statements In Bash

Using Shell Pattern Matching/Wildcards

In this final example I will show you how to use shell pattern matching (for example [1-3]) and wildcards (for example [1-3]*). You can also add things to the beginning and end of the shell patterns and wildcards for example hello*itty would match hellokitty.

How To Use Case Statements In Bash

I hope you enjoyed this quick and easy guide on using case statements in bash. Please don’t forget to like/comment/share! =)

Leave a Reply

Your email address will not be published. Required fields are marked *