Using Switch Case in Unix Shell Scripting: Case-esac Statement

By Vijay

By Vijay

I'm Vijay, and I've been working on this blog for the past 20+ years! I’ve been in the IT industry for more than 20 years now. I completed my graduation in B.E. Computer Science from a reputed Pune university and then started my career in…

Learn about our editorial policies.
Updated March 9, 2024

Overview of Unix Switch Case Statements:

In this tutorial, we will see how a switch case block can be used when creating conditional flow depending on the various values of a single expression.


Switch Case in Unix Shell Scripting

Unix Shell The case-esac Statement

Unix Video #16:

The Shell Switch Case Syntax and Examples:

case <word> in
 <first pattern>)
 <statements>
 ;;
 <second pattern>)
 <statements>
 ;;
 *)
 <default statements>
 ;;
 esac

Here, the value of the word expression is matched against each of the choice patterns.  If a match is found then the corresponding statements are executed until the ‘;;’ statement is encountered.  If there is no match, the default statements under ‘*)’ are executed.

The following is an example of a switch case program:

 echo “Enter a number”
 read num
 case $num in
 [0-9])
 echo “you have entered a single digit number”
 ;;
 [1-9][1-9])
 echo “you have entered a two-digit number”
 ;;
 [1-9][1-9][1-9])
 echo “you have entered a three-digit number”
 ;;
 *)
 echo “your entry does not match any of the conditions”
 ;;
 Esac

To know more about working with loops in Unix, check out our upcoming tutorial.

PREV Tutorial | NEXT Tutorial

Was this helpful?

Thanks for your feedback!

Leave a Comment