This article will introduce Case statement in Bash. It is similar to Switch-Case in other languages.
1. Syntax
The syntax of Case statement is as follows.
- If there is a
pattern_X)
that matches theexpression
, the statements in that block will be executed - You can use the
|
operator to apply multiple conditions to one pattern, likepattern_3|pattern_4)
- Items that do not match the condition can be handled in
*)
case expression in
pattern_1)
statements
;;
pattern_2)
statements
;;
pattern_3|pattern_4|pattern_5)
statements
;;
*)
statements
;;
esac
2. Example of Case statement
You can use the Case statement to perform the conditional statement corresponding to the var.
#!/bin/bash
var=1
case $var in
1)
echo "Apple"
;;
2)
echo "Grape"
;;
3)
echo "Kiwi"
;;
esac
Output:
$ bash example.sh
Apple
3. Case statement with User input
In this example, it takes in User Input and prints out a specific string.
If there is no matching pattern, it is handled from *)
.
#!/bin/bash
read -p "Yes or No? : " Answer
case $Answer in
Yes|yes|y|Y)
echo "You typed 'Yes'"
;;
No|no|N|n)
echo "You typed 'No'"
;;
*)
echo "Invalid answer"
esac
Output:
$ bash example.sh
Yes or No? : Y
You typed 'Yes'
$ bash example.sh
Yes or No? : No
You typed 'No'
$ bash example.sh
Yes or No? : NO
Invalid answer
4. Case statement with Regex
This is an example of using regular expressions.
#!/bin/bash
read -p "Type something : " Answer
case $Answer in
a?)
echo "a? pattern"
;;
b*)
echo "b* pattern"
;;
c[def])
echo "cd | ce | cf"
;;
*)
echo "Invalid answer"
;;
esac
?
: It means one character. The patterna?
matches when it starts with an 'a' and is followed by one character.*
: It means one or more of any characters. The patterna*
matches when there is one or more characters after an 'a'.[abc]
: It means one of the characters a or b or c. The patterna[bc]
is judged to matchab
andac
.
This is the result of above example.
$ bash example.sh
Type something : a
Invalid answer
$ bash example.sh
Type something : a1
a? pattern
$ bash example.sh
Type something : a22
Invalid answer
$ bash example.sh
Type something : bbaabbaa
b* pattern
$ bash example.sh
Type something : cd
cd | ce | cf
$ bash example.sh
Type something : cdd
Invalid answer
Related Posts
- How to measure elapsed time in Bash
- Ceil, Floor, Round off a devided number in Bash
- Check if a number is Positive or Negative in Bash
- How to Print a Variable in Bash
- Number Comparison Operators in Bash
- Convert between Uppercase and Lowercase in Bash
- Check if a File or Directory exists in Bash
- How to extract substring in Bash
- Bash Case Statement with examples
- How to use Command Line Arguments in Bash
- How to use Arrays in Bash
- How to Compare strings in Bash Shell
- if..else statement in Bash
- Add, Subtract, Multiply, Division with Numbers in Bash
- Bash For, Whlie Loop Examples
- How to Pass and Use command line arguments in Bash