您的位置:首页 > 运维架构 > Linux

Linux下Shell的for循环语句N种写法

2021-02-28 22:44 1001 查看

1
运维人员,不管是应用运维,还是数据库运维,系统运维人员,都会掌握一门编程语言,而shell脚本语言是运维人员最常用的,for循环又是shell脚本出现频率最高的,下面就介绍一下Shell的for循环语句N种写法。

循环输出50个数字
第一种写法

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

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

第二种写法

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

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

第三种写法

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

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

第四种写法

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

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

字符性循环
第一种写法

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

第二种写法

[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

第三种写法

[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

第四种写法

[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

这个技能你get了吧

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: