bash編程之while和until循環、變量替換

一、循環體

while 測試條件; do
  語句1
  語句2
  ...
done

while [ $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 $Sum

while循環

#!/bin/bash
Sum=0
Count=1

while [ $Count -le 100 ]; do
  let Sum+=$Count
  let Count++
done

echo $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=$?
done

echo "hadoop is here."

 


until who | grep "^hadoop" &> /dev/null; do     命令可直接作爲判斷條件 無需兩端中括號
  date
  sleep 5
done

echo "hadoop is here."

 


who | grep "^hadoop" &> /dev/null
RetVal=$?

while [ $RetVal -ne 0 ]; do
  date
  sleep 5
  who | grep "^hadoop" &> /dev/null
  RetVal=$?
done

echo "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}  用戶未輸入時立即使用默認值

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章