EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login

Switch Case in Shell Scripting

By Priya PedamkarPriya Pedamkar

Home » Software Development » Software Development Tutorials » Shell Scripting Tutorial » Switch Case in Shell Scripting

Switch Case in Shell Scripting

Introduction to Switch Case in Shell Scripting

When we need to perform multilevel checks we can use multiple if and else conditions or nested if-else branches but when we need to perform all conditional operations on a particular variable then it better to use switch case. In shell scripting switch case is represented using keywords case and esac which will do multilevel branching and checking in a better way than multiple if-else conditions. Switch case will need an expression which it needs to evaluate and need to perform multiple operations based on the outcome of the expression. So, we will use a switch case conditional statement when we want to perform different operations on the outcome of a single expression.

Syntax for Switch Case in Shell Scripting

The syntax for the switch case in shell scripting can be represented in two ways one is single pattern expression and multi-pattern expression let’s have a look now.

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

First Syntax Method

Now, we will have a look at the syntax of the switch case conditional statement with a single pattern.

Syntax:

case $var in pattern) commands to execute;;
pattern1) commands to execute;;
pattern2) commands to execute;;
pattern3) commands to execute;;
*)
Default condition and commands to execute;;
esac

In the above switch case syntax, $var in the pattern is a conditional expression if it evaluates to true commands corresponding to it will execute like that it will check for all conditional patterns if nothing satisfies or evaluates to true then commands in default condition will execute. The default condition is optional but it better to have it. When one condition matches then “;;” indicates control needs to go the end of the switch case statement.

Second Syntax Method

Now, we will have a look at the syntax of the switch case conditional statement with multiple patterns.

Popular Course in this category
Sale
Shell Scripting Training (4 Courses, 1 Project)4 Online Courses | 1 Hands-on Project | 18+ Hours | Verifiable Certificate of Completion | Lifetime Access
4.5 (9,039 ratings)
Course Price

View Course

Related Courses
Kali Linux Training (3 Courses, 3+ Projects)Red Hat Linux Training Program (4 Courses, 1+ Projects)

Syntax:

case $var in pattern|pattern1|pattern2) list of commands need to execute;;
pattern3| pattern4| pattern5) list of commands need to execute;;
pattern6) commands need to execute;;
*)
Default condition and statements need to execute
esac

In the above switch case syntax method, we are having a single $var comparing against multiple patterns with an or condition. If one of the condition matches it evaluates to true then corresponding statements will execute until the “;;” which indicates the end of that conditional statement. *) indicates the start of the default condition and statements need to execute and esac indicates the end of the switch case. We can include wild characters, regex in the patterns. The conditional check will happen continuously until it finds a pattern otherwise default statement will execute.

Flow Diagram for Switch Case

The flow diagram of the switch case in shell scripting is like below and we will explain with a simple example too. An example of the switch case statement is explained below.

Code:

fruit = “kiwi”
case $fruit” in “apple”) echo “apple is tasty”;;
“banana”) echo “I like banana”;;
“kiwi”) echo ”Newzeland is famous for kiwi”;;
*)
Echo “default case”;;
esac

Flow Diagram:

Switch Case in Shell Scripting Flow Diagram

In the above switch case example, we have a variable with kiwi as value and we have 3 patterns. It doesn’t satisfy or evaluates to true in the first 2 conditional statements and evaluates to true in the third conditional statement and executes the statement and control reaches the end of the switch case statement. In the above example first, conditional pattern is apple which is not equal to kiwi so it evaluates to false and second one is banana that also doesn’t matches and evaluates to false and the third statement is kiwi and it matches if it also doesn’t matches then it will execute default statement in the switch case and finally it comes to end of the switch case.

Output:

Switch Case in Shell Scripting

How Switch Case Works in Shell Scripting?

We have discussed already what a switch case, its syntax is. Now, we will see in detail how it will work in shell scripting. Initially, we initialize a variable with an expression or value and conditional statement checks whether it satisfies any condition, if yes then it will execute the corresponding commands until it finds the ;; which indicates the end of the commands of that condition. It will check the condition until it satisfies otherwise it will exit the switch case. If there is a default case then it will execute the commands in it instead of exiting from the switch case. Let’s have a simple example and see how it works as below:

Let’s have a simple example and see how it works as below:

Code:

mode = “jeep”;
case $mode in “lorry") echo "For $mode, rent is Rs.40 per k/m.";;
"jeep") echo "For $mode, rent is Rs.30 per k/m.";;
*) echo "Sorry, I cannot get a $mode rent for you!";;
esac

In the above example, the variable mode is initialized with jeep and it checks all the conditions in switch case and executes the command which it satisfies and then it exits the switch case statement. In this case, it satisfies the condition jeep and executes the commands with a display message and comes out of the switch case statement.

Output:

Switch Case in Shell Scripting working

Examples of Switch Case in Shell Scripting

Let’s have a look different at switch case examples and how they are working, what each example is trying to do with an explanation as follows.

Example #1

In this example, we are trying to tell the computer that it needs to do which backup based on the date.

Code:

NOW=$(date +"%a")
case $NOW in Mon) echo "Full backup";;
Tue|Wed|Thu|Fri) echo "Partial backup";;
Sat|Sun) echo "No backup";;
*) ;;
esac

In the above example, we assigned now with a day and we are checking the statements, here the day is assigned dynamically so the output of this program will change based on the day you execute this program. In this case, it will display partial backup as output.

Output:

Switch Case in Shell Scripting eg2

Example #2

In this example, we are trying to know the fare of a vehicle based on its type like bike, jeep, bicycle, car etc.

Code:

mode = “bike”;
case $mode in "sportscar") echo "For $mode, rent is Rs.20 per k/m.";;
"lorry") echo "For $mode, rent is Rs.50 per k/m.";;
"sumo") echo "For $mode, rent is Rs.30 per k/m.";;
"bicycle") echo "For $mode, rent is Rs. 5 per k/m.";;
*) echo "Sorry, I can not get a $mode rent for you!";;
esac

In the above example, we have a bike in the variable and checking against all the conditions but unfortunately, we didn’t find any match the conditions. So it will execute the default commands of the switch case and come out of it. In this case, it displays a sorry message.

Output:

eg2

Example #3

In this above let’s try to pass an argument to the shell script, and the argument will be compared against the conditions.

Code:

option="${1}"
case ${option} in -f) file="${2}" echo "file name is $file" ;;
-d) dir="${2}" echo "dir name is $dir" ;; *)
esac

In the above example, we will pass an argument to the shell script and according to the argument, it will execute either the file or directory by default it displays the usage of the shell script. If we pass –f and filename it displays the file name, etc.

Output:

eg3

Conclusion

Finally, it’s an overview of the switch case in shell scripting. So far we have discussed what is switch case, its syntax, how it works, its flow using a flow diagram and example, different examples to show use cases of switch case statement in shell scripting. I hope after reading this article you will have a better understanding of switch cases in shell scripting.

Recommended Articles

This is a guide to Switch Case in Shell Scripting. Here we discuss syntaxes, working, and flow diagram of switch case in shell scripting along with its examples and implementation. You may also look at the following articles to learn more –

  1. What is VBScript?
  2. Linux Apps
  3. What is Unix Shell?
  4. PowerShell Operators
  5. Top 5 Uses of Shell Scripting in Various Field 

Shell Scripting Training (4 Courses, 1 Project)

4 Online Courses

1 Hands-on Project

18+ Hours

Verifiable Certificate of Completion

Lifetime Access

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
Shell Scripting Tutorial
  • Shell Scripting Basics
    • What is Shell Scripting
    • Uses of Shell Scripting
    • Shell Scripting Commands
    • Shell Script Parameters
    • Variables in Shell Scripting
    • Shell Script Argument
    • Execute Shell Script
    • Shell Script Set Variable
    • Shell Script Operators
    • Function in Shell Scripting
    • Echo in Shell Scripting
    • if condition in shell script
    • If Statement in Shell Scripting
    • If Else in Shell Scripting
    • Switch Case in Shell Scripting
    • Shell Script Case
    • Loops in Shell Scripting
    • For Loop in Shell Scripting
    • While loop in Shell Scripting
    • Shell Script Set
    • Shell Script Sleep
    • Shell Script Usage
    • Eval in Shell Script
    • Shell Script Read File
    • What is Bash?
    • What is Bash Scripting
    • Bash Shell Script
    • Bash Script Arguments
    • Batch Scripting Commands
    • Bash Script Variables
    • Bash Set Variables
    • Bash Local Variables
    • Bash Variable in String
    • Bash Concatenate Strings
    • Bash Export Variable
    • Bash Alias
    • Bash Trim String
    • Bash Replace String
    • Bash Split String
    • Bash File
    • Shell Scripting Interview Questions
    • Bash String Length
    • Korn Shell Scripting

Related Courses

Shell Scripting Course

Kali Linux Training

Red Hat Training Course

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more

Independence Day Offer - Shell Scripting Training (4 Courses, 1 Project) Learn More