手机版
你好,游客 登录 注册 搜索
背景:
阅读新闻

Bash Shell 入门指导手册

[日期:2012-10-14] 来源:Linux社区  作者:Linux [字体:大 中 小]

case 语句

case 是shell 提供的另一个作为条件判断的语句。
语法:
case expression in
pattern1) execute commands ;;
pattern2) execute commands ;;
...
esac

The keywords here are in, case and esac. The ';;' is used as option terminators. The construct also uses ')' to delimit the pattern from the action.
语法中有case,in和esac三个关键字。
符号;; 是各个选项的结尾标记。
而右括号)用于分割pattern和动作。
Example:
...
echo "Enter your option : "
read i;

case $i in
1) ls -l ;;
2) ps -aux ;;
3) date ;;
4) who ;;
5) exit
esac

注:最后一个选项是不需要;;作结的,当然你喜欢,也可以加上。

另一个例子:
case `date |cut -d" " -f1` in
Mon) commands ;;
Tue) commands ;;
Wed) commands ;;
...
esac

case 可以匹配一个以上的模式(pattern),你可以用通配符来匹配模式;
...
echo "Do you wish to continue? (y/n)"
read ans

case $ans in
Y|y) ;;
[Yy][Ee][Ss]) ;;
N|n) exit ;;
[Nn][Oo]) exit ;;
*) echo "Invalid command"
esac

在以上的例子中,如果你输入 YeS, YES,yEs 或者任何其他的组合,都可以被匹配到。
到此,条件语句的介绍告一段落。

循环语句
while 循环
语法:
while condition_is_true
do
execute commands
done

举例:
while [ $num -gt 100 ]
do
sleep 5
done

while :
do
execute some commands
done

以上代码将会执行一个无限的循环,当然你可以使用while true来代替while : 。
在此我将会介绍和循环相关的关键字:break和continue.
break - 这个关键字能够退出循环,终止执行。
continue - 这个关键字可以暂停当前循环中跟在其后的语句的执行,转而执行下一个循环。
until 循环
如果until 后的条件为false,那么就一直循环地执行do 中的命令。
until false
do
execute commands
done

...
until [ -r myfile ]
do
sleep 5
done

The above code is executed repeatedly until the file myfile can be read.
以上代码将会重复执行,直到myfile是可读的。

linux
相关资讯       Bash Shell  Bash Shell入门  Bash Shell手册 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款