Shell Scripting – Case Statements

 Shell Scripting – Case Statements

Shell scripting case statements – The case statement in shell scripting compares the value of a variable with several different patterns of text or numbers. As a construct the case statement must be ended with an esac command (case spelled backwards).

Here is the syntax for case statements:

pattern1     )   do this


pattern2     )   do this


pattern3     )   do this


* )


Why do we use a Case Statement?

The reason that we use case statements is that they make the coding easy to follow. The easier it is to follow, the easier it is to debug, and coding can get so complex that it is hard to follow the logic. When this happens, try using a Case statement instead of an IF statement.  The more choices that you have with IF statements the more complex the structure.

Here is an example of an IF statement that gets complex with just three choices:

Here it is with a case statement:


The last case * ) is a catch all for anything else that is typed other than what we have coded. The \a beeps to indicate that something is wrong.  Using the pipe symbol ( | ) the script accepts both upper and lower case letters.

The && and || constructs

There are two short cuts that you can use in your coding. The first is the “&& command” completes when the first statement is done the second statement is done just after. The “double pipe command” separates two commands. If the first statement does not run, the second statement runs.

Here are two examples:

(The && Command)

( The || Command)


There are a lot of things that you can do with case statements to get complex results from your coding. Using just with four choices in our simple shell script you can see how complex it can get. Also combining IF and Case statements will give you a lot of flexibility in coding your shell scripts.

Here is the script that we have been working on. I made all of the choices into case statements and here it is zipped up and ready to go. As always, feel free to modify it and see what you can come up with. Drop me an email with your scripts, I’d love to see what you come up with.


How useful was this post?

Click on a star to rate it!

Average rating 5 / 5. Vote count: 1

No votes so far! Be the first to rate this post.

Updated on October 29, 2021