语法:
case $变量名 in
"值 1")
如果变量的值等于值 1,则执行程序 1
;;
"值 2")
如果变量的值等于值 2,则执行程序 2
;;
…省略其他分支…
*)
如果变量的值都不是以上的值,则执行此程序
;;
esac
注意事项:
(1)case 行尾必须为单词“in”,每一个模式匹配必须以右括号“)”结束。
(2)双分号“;;”表示命令序列结束,相当于 java 中的 break。
(3)最后的“*)”表示默认模式,相当于 java 中的 default。
编写脚本:
[root@pwd shdir]# vim case.sh
#!/bin/bash
case $1 in
"1")
echo "星期一"
;;
"2")
echo "星期二"
;;
"3")
echo "星期三"
;;
"4")
echo "星期四"
;;
"5")
echo "星期五"
;;
*)
echo "星期天"
;;
esac
运行脚本:
[root@pwd shdir]# sh case.sh 1
星期一
[root@pwd shdir]# sh case.sh 2
星期二
[root@pwd shdir]# sh case.sh 3
星期三
[root@pwd shdir]# sh case.sh 4
星期四
[root@pwd shdir]# sh case.sh 5
星期五
[root@pwd shdir]# sh case.sh 6
星期天
[root@pwd shdir]# sh case.sh 7
星期天
[root@pwd shdir]#