码迷,mamicode.com
首页 > 其他好文 > 详细

case语法

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

标签: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语法

标签:case语法

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!