语法
while [ condition ] # 注意: 条件为真,while才会循环,条件为假,while停止循环
do
commands
done
while实战1
#!/bin/bash
read -p "NUM: " num1
while [ $num1 -gt 0 ]
do
echo "大于"
done
while实战2
# 打印1-9 当数值为5时停止循环
#!/bin/bash
i=1
while [ $i -lt 10 ]
do
echo $i
if [ $i -eq 5 ];then
break
fi
i=$((i+1))
done
# 打印1-9 当数值为5时跳过当前循环
i=0
while [ $i -lt 10 ]
do
i=$((i+1))
if [ $i -eq 5 ]; then
continue
fi
echo $i
done
while实战3: 99乘法表
1*1=1
1*2=2 2*2=4
1*3=3 2*3=6 3*3=9
.....
#!/bin/bash
n=1
while [ $n -lt 10 ];do
for (( m=1;m<=$n;m++ ));do
echo -n -e '$m*$n=$((n*m))\t'
done
echo
n=$((n+1))
done
while实战4:使用while读取文件中的列,IFS指定默认的列分隔符
#!/bin/bash
IFS=$":"
while read f1 f2 f3 f4 f5 f6 f7
do
echo "$f1 $f2 $f3"
done < /etc/passwd
# 输出
root x 0
bin x 1
daemon x 2
......
while实战5: 使用while遍历文件内容
#!/bin/bash
while read i
do
echo "$i"
done < $1
本文通过五个实例讲解Bash shell中的while循环,涉及输入验证、数字序列打印、乘法表生成、文件操作及内容遍历,帮助理解条件控制在脚本中的应用。
7058

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



