首页 > 其他 > 详细

case语法

时间:2017-01-14 23:25:17      阅读:470      评论:0      收藏:0      [点我收藏+]

语法:

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语法

原文:http://izhouyu.blog.51cto.com/10318932/1891998

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!