语法:
case "字符串变量" in
值1)指令
;;
值2)指令
;;
值*)指令
;;
esac
下面我们来作一个小脚本:
#!/bin/bash
read -p "please input one the number:" a
case "$a" in
1)
echo "you input the number is 1"
;;
2)
echo "you input the number is 2"
;;
[3-9])
echo "you input the number is $a"
;;
*)
echo "you input the number more than 10!"
;;
esac
下面是这个脚本的执行效果:
[[email protected] shell]# sh case.sh
please input one the number:1
you input the number is 1
[[email protected] shell]# sh case.sh
please input one the number:2
you input the number is 2
[[email protected] shell]# sh case.sh
please input one the number:3
you input the number is 3
[[email protected] shell]# sh case.sh
please input one the number:4
you input the number is 4
[[email protected] shell]# sh case.sh
please input one the number:10
you input the number more than 10!
[[email protected] shell]#
如果我们用if语句去实现的话是这样的
#!/bin/bash
read -p "please input one the number:" a
if [ $a -eq 1 ];then
echo "you input the number is 1"
elif [ $a -eq 2 ];then
echo "you input the number is 2"
elif [ $a -ge 3 -a $a -le 9 ];then
echo "you input the number is $a"
else
echo "you input the number more than 10!"
fi
"case_if.sh" 11L, 283C 已写入
[[email protected] shell]# sh case_if.sh
please input one the number:1
you input the number is 1
[[email protected] shell]# sh case_if.sh
please input one the number:2
you input the number is 2
[[email protected] shell]# sh case_if.sh
please input one the number:3
you input the number is 3
[[email protected] shell]# sh case_if.sh
please input one the number:4
you input the number is 4
[[email protected] shell]# sh case_if.sh
please input one the number:10
you input the number more than 10!
通过上面我们可以知道,其实用case的话比较快,因为它不用比较,其实if的功能case可以实现,只是有时候用case比较麻烦,所以就用if语句