shell编程之循环语句
1、语法结构:
for var in list
#每次循环,一次把列表list中的一个值赋给循环变量
do
commands
done #循环结束标志
几点说明:
1、列表list可以是命令替换,变量名替换、字符串、文件名列表(可包含通配符)
2、for循环执行的次数取决于列表list中单词的个数
3、for循环体中一般要出现循环变量,但也可以不出现。
1 #! /bin/bash 2 3 for i in $* #位置参数列表,且"1 2" 3还是输出 1 2 3.不会因为“”分割 4 #for i in "$*" # 1 2 3被当作一个参量 5# for i in $@ #与$*一样 6 #for i in "$@" #"1 2" 3只有两个参数 1 2 3 7 do 8 echo value is i 9 done
#统计当前文件目录下有多少个文件 #! /bin/bash counter=0 for f in * do counter=$[$counter+1] done echo There are $counter files in `pwd`
2、类似于C语言的for循环语句
for ((expr1;expr2;expr3))
do
...
done
#打印*形三角 1 #! /bin/bash 2 3 if [ $# -ne 1 ];then 4 echo ' Usage: $0 <n> ' 5 exit 1 6 fi 7 8 if [ $1 -lt "5" -o $1 -gt "15" ];then 9 echo ' where 5<=n<=15 ' 10 exit 1 11 fi 12 13 for ((i=0;i<$1;i++)) 14 do 15 for ((j=0;j<$[$1-$i-1];j++)) 16 do 17 echo -n " " #no enter。打印空格 18 done 19 for ((j=0;j<$[2*$i+1];j++)) 20 do 21 echo -n "*" 22 done 23 echo -ne "\n" 24 done
3、while循环语句
while expr
do
commands
done
1 #! /bin/bash 2 3 lines=$1 4 curline=0 5 while [ $curline -lt $lines ] 6 do 7 nSpaces=$[$lines-$curline-1] 8 while [ $nSpaces -gt 0 ] 9 do 10 echo -n " " 11 nSpaces=$[$nSpaces-1] 12 done 13 nStars=$[2*$curline+1] 14 while [ $nStars -gt 0 ] 15 do 16 echo -n "*" 17 nStars=$[$nStars-1] 18 done 19 echo 20 curline=$[$curline+1] 21 done
3、until循环
until循环不同于while循环,当expr为假的时候,执行循环体,直到expr为真(0)时退出循环
until expr
do
commands
done
1 #! /bin/bash 2 3 counter=0 4 5 until [ $counter -eq 3 ] 6 do 7 echo AAA 8 sleep 1 9 counter=$[$counter+1] 10 done
4、break [n] continue[n]
5、exit命令:exit n用于退出脚本或当前进程。n是一个从0到255的整数。0表示成功,非0表示遇到某种失败而非正常退出。该整数被保存在状态变量$?中。
6、sleep命令:sleep n
7、select 循环与菜单
语法结构:
select var in list
do
commands
done
select循环主要用于创建菜单,按数字顺序排列的菜单项将显示在标准错误上,并显示PS3提示符,等待用户输入。
1、用户输入菜单列表中的某个数字,执行相应命令
2、用户输入被保存在内置变量REPLY中
1 #! /bin/bash 2 PS3="favarite pets:" 3 select var in Dogs Cats Birds 4 do 5 case $var in 6 Dogs) 7 echo Dogs are mmy favarite pet 8 #break 9 ;; 10 Cats) 11 echo Cats are mmy favarite pet 12 ;; 13 Birds) 14 echo Birds are mmy favarite pet 15 ;; 16 *) 17 echo none of mmy favarite pet 18 ;; 19 esac 20 #break 21 done
[root@tlinux shell]# ./09.sh
1) Dogs
2) Cats
3) Birds
favarite pets:1
Dogs are mmy favarite pet
favarite pets:2
Cats are mmy favarite pet
favarite pets:3
Birds are mmy favarite pet
favarite pets:
2) Cats
3) Birds
favarite pets:1
Dogs are mmy favarite pet
favarite pets:2
Cats are mmy favarite pet
favarite pets:3
Birds are mmy favarite pet
favarite pets: