日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

bash shell while语法

發布時間:2025/4/16 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 bash shell while语法 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

在編寫腳本時,一定要注意空格

基本語法:

while [ condition ] docommand1command2command3 done condition為true時命令1到命令3將會一直執行,知道條件為false ,例如: #!/bin/bash x=1 while [ $x -le 5 ] doecho "Welcome $x times"x=$(( $x + 1 )) done

Here is a sample shell code to calculate factorial using while loop:

#!/bin/bash counter=$1 factorial=1 while [ $counter -gt 0 ] dofactorial=$(( $factorial * $counter ))counter=$(( $counter - 1 )) done echo $factorial

To run just type:
$ chmod +x script.sh
$ ./script.sh 5
Output:

120

While loops are frequently used for reading data line by line from file:

#!/bin/bash FILE=$1 # read $FILE using the file descriptors exec 3<&0 exec 0<$FILE while read line do# use $line variable to process lineecho $line done exec 0<&3

You can easily evaluate the options passed on the command line for a script using while loop:

...... .. while getopts ae:f:hd:s:qx: option docase "${option}"ina) ALARM="TRUE";;e) ADMIN=${OPTARG};;d) DOMAIN=${OPTARG};;f) SERVERFILE=$OPTARG;;s) WHOIS_SERVER=$OPTARG;;q) QUIET="TRUE";;x) WARNDAYS=$OPTARG;;\?) usageexit 1;;esac done ....... ..

How do I use while as?infinite loops?

Infinite for while can be created with empty expressions, such as:

#!/bin/bash while : doecho "infinite loops [ hit CTRL+C to stop]" done

Conditional while loop exit with break statement

You can do early exit with the break statement inside the whil loop. You can exit from within a WHILE using break. General break statement inside the while loop is as follows:

while [ condition ] dostatements1 #Executed as long as condition is true and/or, up to a disaster-condition if any.statements2if (disaster-condition)thenbreak #Abandon the while lopp.fistatements3 #While good and, no disaster-condition. done

In this example, the break statement will skip the while loop when user enters -1, otherwise it will keep adding two numbers:

#!/bin/bashwhile : doread -p "Enter two numnbers ( - 1 to quit ) : " a bif [ $a -eq -1 ]thenbreakfians=$(( a + b ))echo $ans done

Early?continuation with the continue?statement

To resume the next iteration of the enclosing WHILE loop use the continue statement as follows:

while [ condition ] dostatements1 #Executed as long as condition is true and/or, up to a disaster-condition if any.statements2if (condition)thencontinue #Go to next iteration of I in the loop and skip statements3fistatements3 done


while [ condition ] dostatements1 #Executed as long as condition is true and/or, up to a disaster-condition if any.statements2if (disaster-condition)thenbreak #Abandon the while lopp.fistatements3 #While good and, no disaster-condition. done

總結

以上是生活随笔為你收集整理的bash shell while语法的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。