linux shell迴圈樣本

來源:互聯網
上載者:User

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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.