标签:
1. for循环语句
1.1. 语法格式:
for var in list do commands done
for ((表达式)) do commands done
1.2 简单示例:
#!/bin/sh #从直接列表读取 echo "从直接列表读取" for var in 1 2 3 do echo "$var" done echo "\n" #从变量读取 echo "从变量读取" list="a b c" for var in $list do echo "$var" done echo "\n" #从命令读取 echo "命令读取" for var in `cat test.txt` do echo "$var" done echo "\n" #从目录读取 echo "从目录读取" for var in ~/Desktop/Hello* do echo "$var" done #for+表达式结构 sum=0 echo "for+表达式结构" for((i=0;i<=10;i++)) do ((sum+=i)) done echo "sum is :$sum" echo "\n"运行结果:
1.3 分隔符
1.3.1 默认分隔符号:空格,制表符,换行符
1..3.2 修改分隔符,e.g. 设置分号 “;”为分隔符:IFS=$";"
备注:分隔符的设置对于直接列表无效,因为对于直接列表来说,是一个已经分隔好的列表了。
2. while与until语句
2.1 while语句,表示当条件满足时,执行循环,语句结构如下:
while test command do commands done
until test command do commands done2.2 简单示例
#!/bin/sh #while结构 echo "while循环结构" var=0 while [ $var -lt 3 ] do var=$[ $var + 1 ] echo "$var" done echo "\n" #until结构 echo "until循环结构" var=0 until [ $var -eq 3 ] do var=$[ $var + 1 ] echo "$var" done echo "\n"运行结果:
3. 循环的嵌套和控制
3.1 通过循环的嵌套方式输出乘法口诀表,e.g:
#!/bin/sh for (( i=1; i<=9; i++ )) do for (( j=1; j<=i; j++ )) do printf '%dx%d=%-3d' $i $j $[$i*$j] done echo done运行结果:
3.2 通过break语句和continue语句可以可以进行循环控制,break语句的作用为跳出循环,continue语句的作用时跳出当前循环,继续下一个循环,e.g:
#!/bin/sh #break语句,跳出循环 echo "break语句,跳出循环" for (( i=1; i<=5; i++ )) do if [ $i -eq 3 ] then break fi echo "$i" done echo #continue语句,跳出当前循环,继续下一次循环 echo "continue语句,跳出当前循环,继续下一次循环" for (( i=1; i<=5; i++ )) do if [ $i -eq 3 ] then continue fi echo "$i" done运行结果:
标签:
原文地址:http://blog.csdn.net/swordgirl2011/article/details/51327471