for迴圈樣本
for迴圈文法:
for VARIABLE in 1 2 3 4 5 .. Ndo command1 command2 commandNdone
#!/bin/bashfor i in 1 2 3 4 5doecho "Welcome $i times"done
bash version 3.0+版本
#!/bin/bash for i in {1..5}do echo "Welcome $i times"done
bash version 4版本
#!/bin/bashecho "Bash version ${BASH_VERSION}..."for i in {0..10..2} do echo "Welcome $i times" done
含有“seq”命令的文法樣本
#!/bin/bashfor i in $(seq 1 2 20)do echo "Welcome $i times"done
for迴圈的三個運算式
文法如下:
for (( EXP1; EXP2; EXP3 ))do command1 command2 command3done
樣本如下:
#!/bin/bashfor (( c=1; c<=5; c++ ))do echo "Welcome $c times..."done
效果:
Welcome 1 timesWelcome 2 timesWelcome 3 timesWelcome 4 timesWelcome 5 times
for的無限迴圈
#!/bin/bashfor (( ; ; ))do echo "infinite loops [ hit CTRL+C to stop]"done
break條件陳述式
for I in 1 2 3 4 5do statements1 #Executed for all values of ''I'', up to a disaster-condition if any. statements2 if (disaster-condition) then break #Abandon the loop. fi statements3 #While good and, no disaster-condition.done
下面的shell指令碼將通過在/ etc目錄中儲存的所有檔案。 for迴圈將放棄當/ etc / resolv.conf的檔案中找到。
#!/bin/bashfor file in /etc/*do if [ "${file}" == "/etc/resolv.conf" ] then countNameservers=$(grep -c nameserver /etc/resolv.conf) echo "Total ${countNameservers} nameservers defined in ${file}" break fidone
continue條件陳述式
for I in 1 2 3 4 5do statements1 #Executed for all values of ''I'', up to a disaster-condition if any. statements2 if (condition) then continue #Go to next iteration of I in the loop and skip statements3 fi statements3done
利用這個指令碼在命令列中指定的所有檔案名稱的備份。如果。bak檔案存在,它會跳過cp命令。
#!/bin/bashFILES="$@"for f in $FILESdo # if .bak backup file exists, read next file if [ -f ${f}.bak ] then echo "Skiping $f file..." continue # read next file and skip cp command fi # we are hear means no backup file exists, just use cp command to copy file /bin/cp $f $f.bakdone