N ways to write for loop statements in Shell under Linux

1
Operation and maintenance personnel, whether it is application operation and maintenance, or database operation and maintenance, or system operation and maintenance personnel, will master a programming language, and shell scripting language is the most commonly used by operation and maintenance personnel, and for loops are the most frequent occurrence of shell scripts , The following introduces the N ways of writing Shell's for loop statement.

The first way to write 50 numbers in a loop

[root@localhost ~]# cat 1.sh 
#!/bin/bash

for ((i=1;i<=50;i++));
do
echo $i
done

The second way of writing

[root@localhost ~]# cat 2.sh 
#!/bin/bash

for i in $(seq 1 50)
do
echo $i
done

The third way of writing

[root@localhost ~]# cat 3.sh 
#!/bin/bash

for i in {1..50}
do
echo $i
done

The fourth way of writing


[root@localhost ~]# cat 4.sh
#!/bin/bash

awk 'BEGIN{for(i=1; i<=50; i++) print i}'

The first way of writing character cycle

a.txt文件内容为1到50数字列表
[root@localhost ~]# cat a.txt
1
2
3
4
5
...
50

[root@localhost ~]# cat 5.sh
#!/bin/bash

for i in `cat a.txt`
do
echo $i
done

The second way of writing

[root@localhost ~]# cat 6.sh
#!/bin/bash

for i in `ls`

do
echo $i
done

[root@localhost ~]# ./6.sh
sql.txt.gz
sysbench-1.0.17-2.el7.x86_64.rpm
test.log

The third way of writing

[root@localhost ~]# cat 7.sh
#!/bin/bash

list_str="test1 test2 test3 test4"
for i in $list_str;
do
echo $i
done

[root@localhost ~]# ./7.sh
test1
test2
test3
test4

The fourth way of writing


[root@localhost ~]# cat 8.sh
#!/bin/bash

for file in $(ls)
do
echo $file
done

[root@localhost ~]# ./8.sh
sql.txt.gz
sysbench-1.0.17-2.el7.x86_64.rpm
test.log

Have you got this skill?

Guess you like

Origin blog.51cto.com/15061930/2642088