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是可读的。
