# Case Statements in Linux Shell Scripting
In Linux shell scripting, the `case` statement is a powerful tool for handling multiple conditions in a more readable and structured way. It provides an alternative to a series of `if-elif-else` statements when dealing with different values of a variable.
## 1. Basic Syntax
The basic syntax of a `case` statement in bash is as follows:
```bash
case variable in
pattern1)
# code to be executed if variable matches pattern1
;;
pattern2)
# code to be executed if variable matches pattern2
;;
pattern3)
# code to be executed if variable matches pattern3
;;
*)
# code to be executed if variable matches none of the patterns
;;
esac
#!/bin/bash
fruit="apple"
case $fruit in
"apple")
echo "It's a delicious apple."
;;
"orange")
echo "It's a juicy orange."
;;
"banana")
echo "It's a ripe banana."
;;
*)
echo "Unknown fruit."
;;
esac
#!/bin/bash
score=85
case $score in
[90-100])
echo "Excellent! You scored an A."
;;
[80-89])
echo "Good job! You scored a B."
;;
[70-79])
echo "Not bad. You scored a C."
;;
*)
echo "You need to improve."
;;
esac
#!/bin/bash
file="example.txt"
case $file in
*.txt)
echo "It's a text file."
;;
*.pdf)
echo "It's a PDF document."
;;
*)
echo "Unknown file type."
;;
esac
- Each pattern should end with
;;
to indicate the end of that particular case. - The
*)
at the end serves as the default case, similar to theelse
statement inif-elif-else
constructs. - Use of square brackets allows for pattern matching using ranges or wildcards.
These examples illustrate the basic usage of case
statements in Linux shell scripting. You can customize and expand upon these templates based on your specific requirements and use cases.