Linux 仅回显有效用户

Linux 仅回显有效用户,linux,bash,shell,Linux,Bash,Shell,Bash新手问题:我希望这个脚本只回显给定列表中有效用户ID的用户,而不回显无效用户ID 以下是我目前掌握的情况: #!/bin/bash while IFS= read -r line do id "$line" if [ $? -eq 1 ] ; then echo $line else echo "$line is not valid user ID" >&2 fi do

Bash新手问题:我希望这个脚本只回显给定列表中有效用户ID的用户,而不回显无效用户ID

以下是我目前掌握的情况:

#!/bin/bash

while IFS= read -r line
    do
        id "$line"

        if [ $? -eq 1 ] ; then

        echo $line

        else

        echo "$line is not valid user ID" >&2
fi
    done < "$1"
理想情况下,它会回显如下结果:

wwirls
otheruserid
admin
谢谢你的帮助

id "$line" &> /dev/null
可能是你想要做的最小的改变。这意味着将
id
(包括任何错误消息)的输出发送到位存储桶(
/dev/null
)。但是,您的测试感觉是向后的-
$?
成功时为
0
,失败时为
1

现在,恰巧,
if
会自动查看
$?
。因此,您可以将其缩短为:

if id "$line" &> /dev/null    # Find out if the user exists, without printing anything
then
    echo "$line"              # The user exists (`id` succeeded)
else
    echo "$line is not valid user ID" >&2     # No such user
fi
编辑2如果不需要
无效
输出,则可以使用替换整个
If
fi

id "$line" &> /dev/null && echo "$line"

如果
&&
之前的命令成功,bash将在
&&
之后运行该命令,您就可以摇滚了。我会在一分钟内回答这个问题,并感谢您的帮助和优雅的解决方案。Cheers@Dan很乐意帮忙!我要删除我的评论只是为了清理一下。
id "$line" &> /dev/null && echo "$line"