Case Statements in Bash Scripting | 2022

 Case Statements in Bash Scripting  | 2022

Case Statements in Bash Scripting  | 2022

Introduction:- 

The case statements in bash are generally used as an alternative to if-else statements, it checks for the value or the pattern if it matches then the block gets executed. 

The case statement checks the input value until it finds the corresponding pattern and executes the command related to that input value. Thus, it is an excellent choice for creating menus where users select an option that executes a corresponding action.

Case statement syntax


case EXPRESSION in

PATTERN_1)
STATEMENTS
;;

PATTERN_2)
STATEMENTS
;;

PATTERN_3|PATTERN_4|PATTERN_N)
STATEMENTS
;;
PATTERN_N)
STATEMENTS
;;

*)
STATEMENTS
;;
esac


  1. Each case statement starts with a case keyword, followed by an expression to which we want to evaluate

  2. We can have different patterns to which we want to compare our expression to be compared.

  3. We can also have different patterns in the same way by separating them with the | operator. 

  4. We can also supply regex(Regular Expressions) in the patterns.

  5. Every pattern must end with two semicolons(;;) ( representing termination as if we use break keyword in C Programming  ). 

  6. The last one is a wildcard or a default case ( *) if none of the above matches then the default case runs. 

Example for the case statement


#!/bin/bash


echo "Which browser are you currently using??"
echo "Chrome, Firefox, Brave, Tor, Other"
read -p "Enter your browser:- " browser

case $browser in

Chrome|chrome)
echo "Thats Cool, but common you should try some other"
;;

Firefox | firefox)
echo "That Good"
;;

Brave | brave)
echo "Ohh you want ad blocking by default"
;;

Tor | tor)
echo "You are serious about privacy"
;;

*)
echo "Sounds Good, I will try that"
;;
esac


This is a simple bash script asking users which browser they using and giving user feedback according to that. 


$ bash bashscript.sh

Output:- 

Case Statements in Bash Scripting  | 2022

As you can see we have used the case statements effectively in our bash script, we can also do this thing using Conditional statements, but this is another way of doing stuff. 

Conclusion:- 

  • We learned the use of case statement

  • We saw the syntax for the case statements, what can we supply them as a programmer.

  • We used the case statement as an example asking users which browser are they using.
Next Post Previous Post
No Comment
Add Comment
comment url