-----------------------------------------------------------------Sun-------------------------------------------------------------------
一、循环
1.for循环
for week in Monday Tuesday Wednesday Thursday Friday Saturday Sunday #<span style="color:#CC66CC;">每个占一行</span>
do
echo $week
done
for week in<strong><span style="color:#CC66CC;"> "</span></strong>Monday Tuesday Wednesday Thursday Friday Saturday Sunday<span style="color:#CC66CC;"><strong>"</strong></span> #<span style="color:#CC66CC;">打印在一行</span>
do
echo $week
done
结果为:
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday
Monday Tuesday Wednesday Thursday Friday Saturday Sunday
2.while循环
#!/bin/bash
var=0
lim=10
while [ "$var" -lt "$lim" ]
do
echo -n "$var"
var=`expr $var + 1`
# 或者 var=$((var +1))
# 或者 let "var += 1" 等等
done
从0递增到10
3.until循环
#!/bin/bash
e=end
until [ "$var" = "$e" ]
do
echo "($e to exit)"
read var
echo "#1 = $var"
done
输入的字符串为 end 时,退出。
二、嵌套循环
#!/bin/bash
out=1
for a in 1 2 3 4 5
do
echo "$out in outer"
in=1
for b in 1 2
do
echo "$in in inner"
let in+=1
done
let out+=1
done
#!/bin/bash
out=1
for a in 1 2 3 4 5
do
echo "$out in outer"
in=1
for b in 1 2
do
echo "$in in inner"
let in+=1
done
let out+=1
done
三、循环控制
break 跳出整个循环
continue 跳出本次循环
四、测试与分支
1.case (in) / esac
在shell中的case结构与C/C++中的switch结构是相同的。它允许通过判断来选择代码块中多条路径中的一条。它的作用和多个if/then/else语句的作用相同,是它们的简化结构,特别适用于创建菜单。
case块以esac(case的反向拼写)结尾。
#!/bin/bash
read key
<span style="color:#CC66CC;"><strong>case "$key" in</strong></span>
[[:lower:]] ) echo "Lower letter";;
[[:upper:]] ) echo "Upper letter";;
[0-9]) echo "Digit";;
* ) echo "Whitepace";;
<strong><span style="color:#CC66CC;">esac</span></strong>
只有当 [] 中出现的被输入,那么输出相应的。 比如输入e,则返回 Lower letter。
2.select
select结构是建立菜单的另一种工具,这种结构是从ksh中引入的。
echo
select fruit in "apple" "pear" "strawberry" "watermelon"
do
echo " your favorite is $fruit"
break
done
结果为:
1) apple
2) pear
3) strawberry
4) watermelon
#? 4
your favorite is watermelon