linux shell中for循环结构

1、循环数字

root@PC1:/home/test# ls
root@PC1:/home/test# for((i = 1; i <= 5; i++)); do echo $i; done
1
2
3
4
5

2、

root@PC1:/home/test# ls
root@PC1:/home/test# for i in $(seq 5); do echo $i; done
1
2
3
4
5

3、

root@PC1:/home/test# ls
root@PC1:/home/test# var="1 2 3 4 5"
root@PC1:/home/test# for i in $var; do echo $i; done
1
2
3
4
5

4、

root@PC1:/home/test# ls
root@PC1:/home/test# awk 'BEGIN{for(i = 1; i <= 5; i++) print i}'
1
2
3
4
5

5、

root@PC1:/home/test# ls
a.txt
root@PC1:/home/test# cat a.txt
2 4 1 5 8
3 1 4 6 5
7 9 8 6 3
6 2 7 3 9
root@PC1:/home/test# for i in $(head -n 1 a.txt); do echo $i; done  ## 按照第一行进行循环
2
4
1
5
8

6、

root@PC1:/home/test# ls
a.txt
root@PC1:/home/test# cat a.txt
2 4 1 5 8
3 1 4 6 5
7 9 8 6 3
6 2 7 3 9
root@PC1:/home/test# for i in $(head -n 2 a.txt); do echo $i; done   ## 按照a.txt的前两行进行循环
2
4
1
5
8
3
1
4
6
5

7、

root@PC1:/home/test# ls
a.txt
root@PC1:/home/test# cat a.txt
2 4 1 5 8
3 1 4 6 5
7 9 8 6 3
6 2 7 3 9
root@PC1:/home/test# for i in $(awk '{print $1}' a.txt); do echo $i; done  ## 按照第一列进行循环
2
3
7
6

8、

root@PC1:/home/test# ls
a.txt
root@PC1:/home/test# cat a.txt
2 4 1 5 8
3 1 4 6 5
7 9 8 6 3
6 2 7 3 9
root@PC1:/home/test# for i in $(awk '{print $1, $2}' a.txt); do echo $i; done  ## 按照前两列进行循环
2
4
3
1
7
9
6
2

9、

root@PC1:/home/test# ls
root@PC1:/home/test# for i in {1..5}; do echo $i; done
1
2
3
4
5

10、

root@PC1:/home/test# ls
test1.txt  test2.txt  test3.txt  test4.txt
root@PC1:/home/test# for i in $(ls); do echo $i; done
test1.txt
test2.txt
test3.txt
test4.txt

11、

root@PC1:/home/test# ls
test1.csv  test1.txt  test2.csv  test2.txt  test3.csv  test3.txt  test4.csv  test4.txt
root@PC1:/home/test# for i in $(ls *.csv); do echo $i; done  ## 对指定文件类型进行循环
test1.csv
test2.csv
test3.csv
test4.csv

12、

root@PC1:/home/test# ls
root@PC1:/home/test# for i in a b c d; do echo $i; done
a
b
c
d

13、

root@PC1:/home/test# ls
root@PC1:/home/test# var="x y z a b"
root@PC1:/home/test# for i in $var; do echo $i; done
x
y
z
a
b

14、

root@PC1:/home/test# ls
a.txt
root@PC1:/home/test# cat a.txt
2_4_1_5_8
3_1_4_6_5
7_9_8_6_3
6_2_7_3_9
root@PC1:/home/test# for i in $(cat a.txt); do a=$(echo $i | cut -d "_" -f 1); b=$(echo $i | cut -d "_" -f 2); echo $(expr $a + $b); done
6
4
16
8
原文地址:https://www.cnblogs.com/liujiaxin2018/p/15806263.html