Shell的while命令

Shell的while命令

while語法結構

while argument; do
    statement
    ...
done

常見用法

  1. 無限循環。
    while中的無限循環使用((1))或者[ 1 ]來實現.
    示例:時間打印
while ((1)); do
    echo `date '+%Y-%m-%d %H:%M:%S'`
    sleep 1
done

示例:計算1到10的和

i=1
sum=0
while ((i<=10));do
    let sum+=i
    let ++i
done
echo $sum
  1. 讀取文件
    經典的用法是搭配重定向輸入,讀取文件的內容。
    示例:打印出使用bash的用戶
while read line;do
    bashuser=`echo $line | awk -F: '{print $1,$NF}' | grep 'bash' | awk '{print $1}'`
    #jugement Bashuser is null or not and print the user who use bash shell
    if [ ! -z $bashuser ];then
        echo "$bashuser"
    fi
done < "/etc/passwd"
  1. 通過管道傳遞給{}(同樣適用於其他語句)
    通過管道把命令組丟給{}
    示例:打印出使用bash的用戶
cat /etc/passwd | {
while read line;do
    #use if statement jugement bash shell user  and print it
    if [ "`echo $line | awk -F: '{print $NF}'`" == "/bin/bash" ];then
        bashuser=`echo $line | awk -F: '{print $1}'`
        echo "$bashuser"
    fi
done
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章