文章目录
一. 带列表的for循环
1. 语法
for var in list
do
command
done
注意:list可以是含有空格或者是换行的字串。
- 换行:则可以读取遍历一个文件;或者命令输出时,带有换行
- 空格:则可以构成一个数组,或者就是字串
2. 例子
2.1. 循环字串
# bash for_test.sh
this is apple
this is orange
this is banana
# cat for_test.sh
#!/bin/bash
fruits="apple orange banana"
for fruit in ${fruits}
do
echo "this is ${fruit}"
done
2.2. 展开或命令替换:数字循环
连续数字相加
cat for_test.sh
#!/bin/bash
# 1. 使用展开
#for num in {1..5}
sum=0
# 2. 使用命令替换
for num in $(seq 1 100)
do
let "sum+=num"
done
echo $sum
从1开始步长为2计算和,即计算1到100的奇数和
# cat for_test.sh
#!/bin/bash
sum=0
for num in $(seq 1 2 100)
do
let "sum+=num"
done
echo $sum
2.3 命令替换(输出换行)作为list
[ test ] # cat for_test.sh
#!/bin/bash
for ls_name in $(ls)
do
ls -l ${ls_name}
done
[ test ]# bash for_test.sh
-rw-r--r-- 1 root hadoop 0 Oct 13 12:35 11
-rw-r--r-- 1 root hadoop 60 Oct 13 12:36 for_test.sh
二. 其他for循环
1. 不带列表的循环
通过参数的方式给for传递变量值
[root@ test]# bash for_test.sh 1 2 3 4
the var is 1
the var is 2
the var is 3
the var is 4
[root@ test]# cat for_test.sh
#!/bin/bash
for var in $@
do
echo the var is $var
done
2. 类C的for循环
[root@ test]# bash for_test.sh
5050
[root@ test]# cat for_test.sh
#!/bin/bash
sum=0
for (( i=1; i<=100; i++ ))
do
let "sum+=i"
done
echo $sum