Switch (Case) Statment in Bash

Switch (Case) Statment in Bash

 Switch (Case) Statment in Bash

The case statement is useful and processes faster than an else-if ladder. Instead of checking all if-else conditions, the case statement directly selects the block to execute based on an input.

Create the first program using the case statement in a shell script. The program takes input from the user and executes statements based on the input value.

Save the above script in case1.sh and execute the script on the bash shell.

chmod +x case1.sh
./case1.sh
Enter your choice [yes/no]:yes
Thank you
Your type: Yes
./case1.sh
Enter your choice [yes/no]:no
Ooops
You type: No
./case1.sh
Enter your choice [yes/no]:anything
Sorry, invalid input

Script Execution Process:

  • Set the execute permission on the shell script.
  • Executed the script the first time and input “yes” to a choice variable. The case matches the string with available options yes). Then execute the code block under the yes option.
  • Executed the script a second time and input “no” to a choice variable. The case matches the string with available options no). Then execute code block under no option.
  • Executed the script a third time and input “anything” to the choice variable. The case found did not match under available options for this string. In this situation case uses wildcard *) and executed statements under it.

Multiple Strings in Case Options

You can define more than one string in the matching pattern under the case statement in shell scripting. Check the sample script here:

Patterns Matching in Case Statement

You can use wildcard characters like *,?, and [] with the case statement. But still, some of the braces expansion does not work. Now, you can set shopt -s extglob to use extended pattern matching.

Save the above script in a shell script execute it with various inputs and study its execution.

Reactions

Post a Comment

0 Comments

close