BASH – Understanding case / esac Statement

INTRODUCTION

The case construct is the shell scripting analog to switch in C/C++. The case command compares the variable specified against the different patterns. If the variable matches the pattern, the shell executes the commands specified for the pattern. The asterisk symbol is the catch-all for values that don’t match any of the listed patterns.

Often you’ll find yourself trying to evaluate the value of a variable, looking for a specific value within a set of possible values. In this scenario, you may end up having to write a lengthy if-then-else statement. Case can act as a rescue here.

SYNTAX

case variable in

pattern1 | pattern2)

commands1
  commands2
;;

pattern3) commands3;;

pattern4) commands4
;;

*) default commands;;


esac

The entire case block ends with an esac (case spelled reverse). This ensures terminates of case statement.

EXAMPLE

Let’s understand the case better with a basic example:


A basic mathematics calculation example with case. Trying to show , how one can put forward 2 options. You can use one option as well, all it need is matching pattern
















TESTING

[root@practice  ]# sh maths.sh
Basic calculator for 2 numbers
Enter 1st number : 10
Enter 2nd number : 1.7
Input operation to be performed : Add or + , Subtract or – , Multiply or * , Division or / : Add
The result of add of 10 & 1.7 is 11.7
[root@practice  ]#

[root@practice  ]# sh maths.sh
Basic calculator for 2 numbers
Enter 1st number : 11
Enter 2nd number : 2.3
Input operation to be performed : Add or + , Subtract or – , Multiply or * , Division or / :
The result of subtract of 11 & 2.3 is 8.7
[root@practice  ]#

[root@practice  ]# sh maths.sh
Basic calculator for 2 numbers
Enter 1st number : 15
Enter 2nd number : 2.74
Input operation to be performed : Add or + , Subtract or – , Multiply or * , Division or / : *
The result of multiply of 15 & 2.74 is 41.10
[root@practice  ]#

[root@practice  ]# sh maths.sh
Basic calculator for 2 numbers
Enter 1st number : 7.4
Enter 2nd number : 2.4
Input operation to be performed : Add or + , Subtract or – , Multiply or * , Division or / : /
The result of division of 7.4 & 2.4 is 3
[root@practice  ]#

[root@practice  ]# sh maths.sh
Basic calculator for 2 numbers
Enter 1st number : 23
Enter 2nd number : 43
Input operation to be performed : Add or + , Subtract or – , Multiply or * , Division or / : Ads
choose from available values

[root@practice  ]#

I hope this is helpful for you, Enjoy

Please share your queries/feedback in commets

Leave a comment