在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 !