Case Statements, Linux Bash Shell.
Syntax
case EXPRESSION in
PATTERN_1)
STATEMENTS ;;
PATTERN_2)
STATEMENTS ;;
PATTERN_N)
STATEMENTS ;;
*)
STATEMENTS ;;
esac
esac is used to complete the sentence.
| operator can be used to separate several patterns.
) operator a pattern list is terminated.
;; needs to be ended in each clause.
* symbol the final pattern to specify the default situation.
The return status is zero if no pattern is found. If not, the exit status is the return.
case in bash simple example:
ubuntu:~/Bash_scripts# vim simple_case.sh
1 #!/bin/bash
2 echo "Enter distro name:"
3 read distro
4 case $distro in
5 ubuntu)
6 echo "Your distro is $distro" ;;
7 fedora)
8 echo "Your distro is $distro" ;;
9 centos)
10 echo "Your distro is $distro" ;;
11 archlinux)
12 echo "Your distro is $distro" ;;
13 *)
14 echo "Invatild input!!!" ;;
15 esac
ubuntu:~/Bash_scripts# bash simple_case.sh
Enter distro name: ubuntu
Your distro is ubuntu
ubuntu:~/Bash_scripts# bash simple_case.sh
Enter distro name: kali
Invalid input!!!
case in bash coding calculator:
ubuntu:~/Bash_scripts# vim simple_calc.sh
1 #!/bin/bash
2 echo "Bash Super Calculator :)"
3 calculate () {
4 read -p "Please enter first number: " n1
5 read -p "Please enter second number " n2
6 echo $n1 $1 $n2 = $(bc -l <<< "$n1$1$n2")
7 }
8 PS3="Choose an operator: "
9 select choice in Add Subtract Multiply Divide Exit; do
10 case $choice in
11 Add )
12 calculate "+";;
13 Subtract )
14 calculate "-";;
15 Multiply )
16 calculate "*";;
17 Divide )
18 calculate "/";;
19 Exit)
20 break;;
21 *)
22 echo "Error $REPLY";;
23 esac
24 done
ubuntu:~/Bash_scripts# bash simple_calc.sh
Bash Super Calculator :)
1) Add
2) Subtract
3) Multiply
4) Divide
5) Exit
Choose an operator: 1
Please enter first number: 1
Please enter second number 2
1 + 2 = 3
Choose an operator: 5
Conclusion
When handling with several options, a bash case statement can be used to reduce complicated conditionals. Build several scripts to compare strings to patterns and execute commands when a match is found.