在shell脚本中,for循环有很多种,今天就对以下几种做一个简单的总结。
1、循环数字
#!/bin/bash for((i=1;i<=10;i++)); do echo $(expr $i * 3 + 1); done
#!/bin/bash for i in $(seq 1 10) do echo $(expr $i * 3 + 1); done
#!/bin/bash for i in {1..10} do echo $(expr $i * 3 + 1); done
#!/bin/bash awk 'BEGIN{for(i=1; i<=10; i++) print i}'
结果:
4 7 10 13 16 19 22 25 28 31
2、循环字符串
#!/bin/bash for i in `ls`; do echo $i is file name! ; done
结果(输出当前文件名):
for.sh
#!/bin/bash for i in $* ; do echo $i is input chart! ; done
结果(输出当前所有入参):
192:shell-home xxx$ sh for.sh param1 param2 param3 param1 is input chart! param2 is input chart! param3 is input chart!
#!/bin/bash for i in f1 f2 f3 ; do echo $i is appoint ; done
结果(循环空格隔开的字符list):
192:shell-home xxx$ sh for.sh f1 is appoint f2 is appoint f3 is appoint
#!/bin/bash list="rootfs usr data data2" for i in $list; do echo $i is appoint ; done
结果(循环list):
192:shell-home xxx$ sh for.sh rootfs is appoint usr is appoint data is appoint data2 is appoint
3、路径查找
#!/bin/bash for file in /Volumes/work/*; do echo $file is file path ! ; done
结果(循环查找当前目录):
192:shell-home xxx$ sh for.sh /Volumes/work/BAK_0_MEDIA is file path ! /Volumes/work/BAK_0_TEXT is file path ! /Volumes/work/apache-maven-3.5.3 is file path ! /Volumes/work/apache-tomcat-9.0.8 is file path ! /Volumes/work/chromedriver is file path ! /Volumes/work/git-repository is file path ! /Volumes/work/intellij-setting-files is file path ! /Volumes/work/justfortest is file path ! /Volumes/work/mavenRepository is file path ! /Volumes/work/pathfordownload is file path ! /Volumes/work/selenium-server-standalone-3.0.0.jar is file path ! /Volumes/work/shell-home is file path !
#!/bin/bash for file in $(ls /Volumes/work) do echo $file is file path ! ; done
结果(循环取出ls的结果):
192:shell-home xxx$ sh for.sh BAK_0_MEDIA is file path ! BAK_0_TEXT is file path ! apache-maven-3.5.3 is file path ! apache-tomcat-9.0.8 is file path ! chromedriver is file path ! git-repository is file path ! intellij-setting-files is file path ! justfortest is file path ! mavenRepository is file path ! pathfordownload is file path ! selenium-server-standalone-3.0.0.jar is file path ! shell-home is file path !