首页 > 代码库 > case语法

case语法

语法:

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

下面是这个脚本的执行效果:

[root@zhouyu shell]# sh case.sh 

please input one the number:1

you input the number is 1

[root@zhouyu shell]# sh case.sh 

please input one the number:2

you input the number is 2

[root@zhouyu shell]# sh case.sh

please input one the number:3

you input the number is 3

[root@zhouyu shell]# sh case.sh

please input one the number:4

you input the number is 4

[root@zhouyu shell]# sh case.sh

please input one the number:10

you input the number more than 10!

[root@zhouyu 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 已写入                                     

[root@zhouyu shell]# sh case_if.sh  

please input one the number:1

you input the number is 1

[root@zhouyu shell]# sh case_if.sh 

please input one the number:2

you input the number is 2

[root@zhouyu shell]# sh case_if.sh

please input one the number:3

you input the number is 3

[root@zhouyu shell]# sh case_if.sh 

please input one the number:4

you input the number is 4

[root@zhouyu shell]# sh case_if.sh 

please input one the number:10

you input the number more than 10!

通过上面我们可以知道,其实用case的话比较快,因为它不用比较,其实if的功能case可以实现,只是有时候用case比较麻烦,所以就用if语句

本文出自 “爱周瑜” 博客,请务必保留此出处http://izhouyu.blog.51cto.com/10318932/1891998

case语法