找出使用Shell脚本的Unix用户名(多个)是否存在



我有以下脚本,该脚本检查了系统中是否存在给定的用户名。

if id "alice" >/dev/null 2>&1; then
        echo "user exists"
else
        echo "user does not exist"
fi

我想检查爱丽丝,鲍勃和卡罗尔是否存在。因此,当我使用以下代码时,我确实会得到正确的结果,但是它会从ID命令中打印出不必要的行。

if id "alice" && id "bob" && id "carol" >/dev/null 2>&1; then
        echo "user exists"
else
        echo "user does not exist"
fi

输出如下:

uid=1001(alice) gid=1002(alice) groups=1005(somegroupname),1002(alice)
uid=1002(bob) gid=1003(bob) groups=1005(somegroupname),1003(bob)
user exists

我想确保,如果爱丽丝,鲍勃或卡罗尔不作为用户出现,我想打印一条有意义的消息

<this_speicific_user> is not present.

您可以使用括号将所有3个命令分组为一个组:

{ id "alice" && id "bob" && id "carol"; } >/dev/null 2>&1

您可以重定向每个命令的stderr:

if id "alice" >/dev/null 2>&1 && id "bob" >/dev/null 2>&1 && id "carol" >/dev/null 2>&1;
then
        echo "user exists"
else
        echo "user does not exist"
fi

oor使用复合命令:

if { id "alice" && id "bob" && id "carol"; } >/dev/null 2>&1; then
        echo "user exists"
else
        echo "user does not exist"
fi

&&一样使用||

{ test1 && test2 && test3 } || else_function

如果您的请求要显示所有未设置的用户,则有点棘手,但请使用否定检查:

{ ! id "alice" && echo "alice absent." } || { ! id "bob" && echo "bob absent." } || { ! id "walter" && echo "walter absent." }

甚至:

absent=false
for user in alice bob walter ; do
   ! id "$user" && echo "$user is absent." && absent=true
done
$absent || echo "All users are present."

我认为一般答案是,如果您想要特定的错误,则需要特定的测试。也就是说,如果您测试(conda || condb || condc),发现哪些情况失败并不是一件直接的。

另外,如果您想全部测试它们,无论如何,都需要将它们分解为单独的测试。否则,如果id "alice"失败,其他人则不会因短路而被测试。

最新更新