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