文章目录
shell的三种循环及循环控制符
#shell的三种循环
for循环,while循环,until循环
#shell的循环控制符
break,continue
#for循环的三种结构
列表
不带列表
类C风格
列表for循环
(do和done之间的叫着循环体)
for variable in {list}
do
command1
command2
done
#使用列表for循环显示5次欢迎(这里的1,2,3,4,5可以是数字,也可以是字符串,但是得用空格分开)
for variable in 1 2 3 4 5 #也可以使用省略的计数方式,这样写 for variable in {1..5}
do
echo "欢迎 $variable"
done
shell中还支持按一定的步数进行跳跃式实现列表for
for variable in {1..100..2} #计算1到100所有奇数之和,也可以这样写 for variable $( seq 1 2 100 )
do
let "a+=variable"
done
echo "$a"
使用列表for循环显示当前目录下的文件,将ls命令的结果列表赋值给file
for file in $( ls )
do
echo "file : $file"
done
[root@localhost ~]# sh ceshi.sh
file : 1
file : 4564
file : 56
file : anaconda-ks.cfg
file : asd
file : ceshi.sh
file : ss
使用列表for循环显示所有的输入参数
echo "共输入了$#个参数"
for canshu in "$*"
do
echo "$canshu"
done
不带列表的for循环
(默认会将脚本输入的参数,按列表传给for循环)(使用较少)
for variable #等价于 for variable "$@"
do
command
done
类C风格的for循环
(也叫着计次循环,一般用于循环次数已知的情况)
for (( expr1; expr2; expr3 ))
#其中表达式expr1为循环变量赋初值的语句
#表达式expr2,决定是否进行循环的表达式,当判断expr2的退出状态为0时,执行do和done之间的循环体
#表达式expr3,是用于改变循环变量的语句
do
command
done
例子1
使用类C风格的for循环计算1到100的奇数之和
for (( i=1; i<=100; i=i+2 ))
do
let "a+=i"
done
echo "$a"
例子2
LIN=5
for (( a=1,b=9; a<=LIN; a++,b-- ))
do
let "temp=a-b"
echo "$a-$b=$temp"
done
注意:下面全部省略表达式也是合法的
for (( ; ; ))
do
command
done
如果文章对你有帮助,欢迎点击上方按钮打赏作者
暂无评论