使用 while 按行遍历文件

在《Bash 脚本编程基础及示例》中介绍过 while 命令的简单使用,现在来说说如何使用 while 命令来按行遍历文件。

示例:找出 ID 号为偶数的用户,显示其用户名、ID 及默认 shell。

#!/bin/bash
while read line; do
    userid=$(echo $line | cut -d: -f3)
    username=$(echo $line | cut -d: -f1)
    usershell=$(echo $line | cut -d: -f7)

    if [ $[$userid%2] -eq 0 ]; then
        echo "$username, $userid, $usershell."
    fi
done < /etc/passwd

其中,read 命令后面的 line 为自定义变量,可以在循环体内引用。

消息盒子

# 暂无消息 #

只显示最新10条未读和已读信息