bash shell while语法
在編寫腳本時,一定要注意空格
基本語法:
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 $factorialTo run just type:
$ chmod +x script.sh
$ ./script.sh 5
Output:
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<&3You 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]" doneConditional 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. doneIn 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 doneEarly?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總結
以上是生活随笔為你收集整理的bash shell while语法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Linux之read命令使用
- 下一篇: Building System之 get