Shell编程学习之循环

shell编程学习之循环

1、for----do.......done第一种循环

-bash-3.2# cat test.sh
#!/bin/bash
for var in 1 2 3 4 5
do
echo $var
done
-bash-3.2# sh test.sh
1
2
3
4
5

2、for----do.......done第二种循环

-bash-3.2# cat test.sh
#!/bin/bash
for var in `seq 5`
do
echo $var
done
-bash-3.2# sh test.sh
1
2
3
4
5

3、for----do.......done第三种循环

-bash-3.2# cat test.sh
#!/bin/bash
for ((i=1;i<=5;i++))
do
echo $i
done
-bash-3.2# sh test.sh
1
2
3
4
5

4、for----do.......done第四种循环

-bash-3.2# cat test.sh
#!/bin/bash
a='frefef'
len=`echo ${#a}`
for ((i=1;i<=$len;i++))
do
echo $i
done
-bash-3.2# sh test.sh
1
2
3
4
5
6

5、for----do.......done第五种嵌入循环

-bash-3.2# cat test.sh
#!/bin/bash
a='fre'
len=`echo ${#a}`
for ((i=1;i<=$len;i++))
do
  for j in 1 2 3
    do
      echo "$i和$j比较大小测试"
  done
done
-bash-3.2# sh test.sh
1和1比较大小测试
1和2比较大小测试
1和3比较大小测试
2和1比较大小测试
2和2比较大小测试
2和3比较大小测试
3和1比较大小测试
3和2比较大小测试
3和3比较大小测试

6、 while.....do.......done

-bash-3.2# cat test.sh
#!/bin/bash
i=1
while [ $i -le 5 ]
do
echo $i
i=$((i+1))      ##实现i++,也可以let
done
-bash-3.2# sh test.sh
1
2
3
4
5

7、until循环

#!/bin/bash
i=1
until [ $i -gt 5 ]
do
echo $i
let i++
done

相关推荐