一、循環體
while 測試條件; do
語句1
語句2
...
donewhile [ $Count -le 5 ]; do
let Count++
done條件滿足時就循環,直到條件不再滿足,則退出循環;
for如何退出循環?遍歷列表中的元素完成;
while循環呢?在循環體改變測試條件相應變量等的值。補充:算術運算符
Sum=$[$Sum+$I]可簡寫爲以下方式
Sum+=$I
+=
-=
*=
/=
%=取餘等Sum=$[$Sum+1]
Sum+=1
let Sum++
let Count--
and --> AND
exit --> EXIT
quit
計算100以內所有正整數的和;
for循環Sum=0
for I in {1..100}; do
Sum+=$I
done
echo $Sumwhile循環
#!/bin/bash
Sum=0
Count=1while [ $Count -le 100 ]; do
let Sum+=$Count
let Count++
doneecho $Sum
二、while循環遍歷文件的每一行:
while read LINE; do
statement1
statement2
...
done < /path/to/somefile例,如果用戶的ID號爲偶數,則顯示其名稱和shell;對所有用戶執行此操作;
while read LINE; do
Uid=`echo $LINE | cut -d: -f3`
if [ $[$Uid%2] -eq 0 ]; then
echo $LINE | cut -d: -f1,7
fi
done < /etc/passwd
三、until循環體
until 測試條件; do
語句1
語句2
...
done條件不滿足就循環,直到滿足時,退出循環;
例,轉換用戶輸入的字符爲大寫,除了quit(遇見quit退出);
read -p "A string: " String
until [ "$String" == 'quit' ]; do
echo $String | tr 'a-z' 'A-Z'
read -p "Next [quit for quiting]: " String
done例,每隔5秒查看hadoop用戶是否登錄,如果登錄,顯示其登錄並退出;否則,顯示當前時間,並說明hadoop尚未登錄:
who | grep "^hadoop" &> /dev/null
RetVal=$?until [ $RetVal -eq 0 ]; do
date
sleep 5
who | grep "^hadoop" &> /dev/null
RetVal=$?
doneecho "hadoop is here."
until who | grep "^hadoop" &> /dev/null; do 命令可直接作爲判斷條件 無需兩端中括號
date
sleep 5
doneecho "hadoop is here."
who | grep "^hadoop" &> /dev/null
RetVal=$?while [ $RetVal -ne 0 ]; do
date
sleep 5
who | grep "^hadoop" &> /dev/null
RetVal=$?
doneecho "hadoop is here."
四、bash編程之變量替換進階:
1.read -p "A string" -t 5 String -t5秒超時後使用默認值但變量本身爲空。
${parameter:-word} 使用默認值但變量爲空
2.${parameter:=word} 使用word並賦予變量此值 ,即賦予默認值。
3.${parameter:?word}不賦予變量任何值 顯示word錯誤信息 輸出到標準錯誤輸出
4.${parameter:+word} 替換值 如果沒有賦值無響應,如果賦值則顯示word值而非變量值但未改變變量值
以上四種均在變量被引用時被觸發,一般來說需要被引用前即賦予默認值,則如下,
String=${String:-word} 用戶未輸入時立即使用默認值