Case Statement
The case statement can be used to match several values against one variable.
The case statement is very useful when you want to provide options for the users.
Example:
Select 1 to say " Hello "
Select 2 to say " Good Bye "
Case Statement in Linux Shell Scripting
Syntax:
case $variable-name in pattern1) { code to execute };; pattern2) { code to execute };; patternN) { code to execute };; *) { code to execute };; esac
Example:
case.sh
#!/bin/sh # Get the value from the user echo "Enter a digit between [ 1 and 4 ]" echo "Enter a value for the variable x:" read x case $x in "1") echo "You have entered One";; "2") echo "You have entered Two";; "3") echo "You have entered Three";; "4") echo "You have entered Four";; *) echo "Sorry, You have entered a value beyond limit";; esac
Result:
./case.sh
Enter a digit between [ 1 and 4 ] Enter a value for the variable x: 4 You have entered Four
The case.sh script takes the value for x from the user and process it accordingly.
In the above example, we entered 4 as the value of x. Try this example script with various other values and see the results.
Also try adding more options to the case statement.
Related posts:
- Shell Scripting Introduction
- Shell Syntax
- Shell - Strings
- Shell - Variables
- Shell - User Intraction
- First Shell Script
- Shell - Arithmetics
- Shell - Case Statement
- Shell - Command Line Arguments
- Shell - For Loop
- Shell - While Loops
- Shell - IF Statements
- Shell - Input Output Redirections
- Shell - Pipes and Filters
- Shell - Process Management
Your IP address1 is: 172.18.0.2
Tutorials
Latest Updates
Follow us
- Tech-Tutorials twitter.com/techcuriosity