运维人员,不管是应用运维,还是数据库运维,系统运维人员,都会掌握一门编程语言,而shell脚本语言是运维人员最常用的,for循环又是shell脚本出现频率最高的,下面就介绍一下Shell的for循环语句N种写法。
循环输出50个数字
第一种写法
[root@localhost ~]# cat 1.sh #!/bin/bashfor ((i=1;i<=50;i++));doecho $idone
第二种写法
[root@localhost ~]# cat 2.sh #!/bin/bashfor i in $(seq 1 50)doecho $idone
第三种写法
[root@localhost ~]# cat 3.sh #!/bin/bashfor i in {1..50}doecho $idone
第四种写法
[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 12345...50[root@localhost ~]# cat 5.sh #!/bin/bashfor i in `cat a.txt`doecho $idone
第二种写法
[root@localhost ~]# cat 6.sh #!/bin/bashfor i in `ls`doecho $idone[root@localhost ~]# ./6.sh sql.txt.gzsysbench-1.0.17-2.el7.x86_64.rpmtest.log
第三种写法
[root@localhost ~]# cat 7.sh #!/bin/bash list_str="test1 test2 test3 test4" for i in $list_str; do echo $idone [root@localhost ~]# ./7.sh test1test2test3test4
第四种写法
[root@localhost ~]# cat 8.sh #!/bin/bash for file in $(ls) do echo $file done[root@localhost ~]# ./8.sh sql.txt.gzsysbench-1.0.17-2.el7.x86_64.rpmtest.log
这个技能你get了吧。