1. Home
  2. Bash
  3. Bash Tutorial
  4. Bash – Case

Bash – Case

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 select 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 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 shell script.
  • Executed the script first time and input “yes” to choice variable. Case matches the string with available options yes). Then executed code block under yes option.
  • Executed the script second time and input “no” to choice variable. Case matches the string with available options no). Then executed code block under no option.
  • Executed the script third time and input “anything” to choice variable. Case found not matches under available options for this string. In this situation case uses wildcard *) and executed statments under it.

Multple Strings in Case Options

You can define more than one string in the matching pattern under case statement in shell scripting. Check 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 still not work. Now, you can set shopt -s extglob to use extended pattern matching.

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

Tags , ,
Was this article helpful to you? Yes 5 No
Advertisement