linux shell编程学习--循环流程while,for,until命令

时间:2022-06-20 20:30:22

作为一种编程语言,流程控制命令是不可缺少的。
bash shell可以使用while,until,for命令实现循环结构。下面逐一介绍。

while命令

while命令语言,语法如下:

while test_commod ;do
user_commods;
done

只要test_commod命令返回0,则执行user_commods命令块;
while循环结束后,整个命令块的返回值,为user_commods命令最后一个命令的返回值,如果user_commods命令块没有执行,则整个返回值为0

while命令的常见用法,就是和read一起按行读取文件,然后对每行数据做些处理

shuanghu@shuanghu:tmp$ cat word.txt 
four
one
three
two
shuanghu@shuanghu:tmp$ cat test_while.sh
#!/bin/bash
#while command
while read line;do
echo $line
done
shuanghu@shuanghu:tmp$ cat word.txt |./test_while.sh
four
one
three
two

for命令

for命令有两种语法
语法一,如下:

for 变量 [in 列表];do
命令块
done

for这种命令语法,有个常见场景就是遍历目录。如遍历统计目录里子目录的大小。

shuanghu@shuanghu:tmp$ cat test_for1.sh 
#!/bin/bash

for name in `ls`;
do
du -sh $name;
done
shuanghu@shuanghu:tmp$./test_for1.sh
8.0K path1
20K path2
4.0K path3

for命令,还有另外一种语法,如下:

for (( 表达式1;表达式2;表达式3));do
命令块
done

for命令的第二种语法,常用场景就是进行已知计数的循环,比如循环输出5个随机数字。
例子如下:

shuanghu@shuanghu:tmp$ cat ./test_for2.sh 
#!/bin/bash
#for commod example
for (( i=0; i<5; ++i));do
echo -e $RANDOM
done
shuanghu@shuanghu:tmp$ ./test_for2.sh
27698
28901
22017
27993
10015

until命令

until命令语法如下:

until condition;
do
命令块;
done

如果condition命令返回非0,则执行命令块;如果condition命令返回0,则退出循环。
until命令的使用场景比较少,但也是有适用场景的,等待某个条件满足,不满足则循环等待。比如,循环监控文件,如果文件大小满足一定条件,则进行备份,否则循环等待。

shuanghu@shuanghu:tmp$cat test_until.sh
#!/bin/bash

#until command

file=logfile
until [ $(ls -l $file | awk '{print $5}') -gt 2000 ]
do
echo "等待5秒,再判断是否满足大小"
sleep 5
done
date=`date +%s`
cp $file "$file-"$date.bak
echo "备份完成"

shuanghu@shuanghu:tmp$./test_until.sh
等待5秒,再判断是否满足大小
等待5秒,再判断是否满足大小
等待5秒,再判断是否满足大小
备份完成