Shell 脚本还提供了 for 循环,它更加灵活易用,更加简洁明了。Shell for 循环有两种使用形式,下面我们逐一讲解。
1.形式一
for((exp1; exp2; exp3))
do
statements
done
说明: - exp1、exp2、exp3 是三个表达式,其中 exp2 是判断条件,for 循环根据 exp2 的结果来决定是否继续下一次循环; - statements 是循环体语句,可以有一条,也可以有多条; - do 和 done 是 Shell 中的关键字。
实例:计算1-100的求和。
#!/bin/bash
declare -i sum
for ((i=1; i<=100; i++))
do
sum+=i
done
echo "The sum is: $sum"
2.形式二
for variable in value_list
do
statements
done
variable 表示变量,value_list 表示取值列表,in 是 Shell 中的关键字。
实例:1-100求和
#!/bin/bash
declare -i sum
for n in {1..100}
do
#双小括号 (( )) 是 Bash Shell 中专门用来进行整数运算的命令
((sum += n))
done
echo "The sum is: $sum"
for in 最常见是实践方式是可以用来接收shell命令的结果,保存到数组中便于遍历。 实例:遍历当前目录下所有文件,并输出文件类型。
#!/bin/bash
for filename in `ls`
do
if [ -f $filename ];then
echo "$filename is file "
elif [ -d $filename ];then
echo "$filename is directory"
else
echo "other"
fi
done
测试运行:
[root@iz2zefozq9h39txdb8s7npz shelldemo]# ./test.sh
haha.txt is file
other
test.sh is file
work is directory