七、for 循环
格式:
for i in item1 item2 item2 do
command
done
1 #!/bin/bash
2 for i in 1 2 3; do
3 echo $i
4 done
执行结果:
python@ubuntu:~/shellscrip$ ./for_test.sh
1
2
3
1 #!/bin/bash
# {1..10..2} 1到10之间的数 步长为2
2 for i in {1..10..2}; do
3 echo $i
4 done
python@ubuntu:~/shellscrip$ ./for_test.sh
1
3
5
7
9
八、while 循环
格式:
while condition;do
command
done
无限循环:
while true;do
command
done
或:
while ;do
command
done
1 #!/bin/bash
2 a=10
3 b=20
4 while [ $a -lt $b ];do
5 echo "$a < $b"
6 break
7 done
注:break 终止循环
执行结果:
python@ubuntu:~/shellscrip$ ./while_test.sh
10 < 20
1 #!/bin/bash
2 a=10
3 b=20
4 i=0
5 while [ $a -lt $b ];do
6 i=$[ i + 1]
7 echo "$a < $b"
8 if [ $i -eq 3 ];then
9 break
10 fi
11
12 done
python@ubuntu:~/shellscrip$ ./while_test.sh
10 < 20
10 < 20
10 < 20
Bash循环结构详解
本文深入探讨了Bash脚本中的两种主要循环结构——for循环和while循环的使用方法及实例。介绍了for循环的格式、参数设定及执行过程,通过具体示例展示了如何遍历数字序列。同时,解析了while循环的条件判断机制,演示了如何利用break语句控制循环的退出。
4033

被折叠的 条评论
为什么被折叠?



