微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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了吧

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐