Bash Shell中主要提供了三种循环方式:for、while和until。
1. for 结构
语法结构:
for var in item1 item2 ... itemN
do
command1
command2
...
commandN
done
变形:
for var in item1 item2 ... itemN; do command1; command2… done;
for (( ; ; ))
do
...
done
for循环的运行flow:是将行1 中的各串行的itemx依次取出,放入指定的变量var中,然后重复do和done之间的commandx,直到所有元素取尽为止。
example:
#!/bin/bash
# description : 列出/var 目录下的所有子目录的size
DIR="/var"
cd $DIR
for i in $(ls $DIR)
do
[ -d $i ] && du -sh $i
done
2.while循环
语法结构:
while condition
do
command
done
无限循环变形:
while :
do
command
done
或
while true
do
command
done
while循环的运行flow:首先进行条件测试,如果condition为真,则进入循环执行command,否则不进入循环。
example:
example1 :
#!/bin/bash
#description:将i从1到5列印
int=1
while(( $int<=5 ))
do
echo $int
# Bash let 命令,执行“表达式”,引用变量时不需要加上$
let "int++"
done
example2 :
#!/bin/bash
#description: 列印test_file 文件
while read line
do
echo ${line}
done < /tmp/test_file
3.until循环
语法结构:
until condition
do
command
done
until 循环的运行flow : 首先进行条件测试,如果condition为假,则进入循环执行command,直到condition为真退出循环。
example:
#!/bin/bash
#description: 将i从0到9列印
a=0
until [ ! $a -lt 10 ]
do
echo $a
a=`expr $a + 1`
done