2024-12-26 06:00:03

检查用户是否存在

我想创建一个脚本来检查用户是否存在。我使用的逻辑如下:

# getent passwd test > /dev/null 2&>1
# echo $?
0
# getent passwd test1 > /dev/null 2&>1
# echo $?
2

如果用户存在,我们就成功,否则用户不存在。我已经把上面的命令在bash脚本如下:

#!/bin/bash

getent passwd $1 > /dev/null 2&>1

if [ $? -eq 0 ]; then
    echo "yes the user exists"
else
    echo "No, the user does not exist"
fi

现在,我的脚本总是说用户存在,不管怎样:

# sh passwd.sh test
yes the user exists
# sh passwd.sh test1
yes the user exists
# sh passwd.sh test2
yes the user exists

为什么上面的条件总是评估为TRUE,并说用户存在?

我哪里说错了?

更新:

在阅读了所有的回复后,我在我的剧本中发现了问题。问题是我重定向get输出的方式。所以我删除了所有重定向的东西,并使get行看起来像这样:

getent passwd $user  > /dev/null

现在我的脚本运行正常。


当前回答

使用sed:

username="alice"
if [ `sed -n "/^$username/p" /etc/passwd` ]
then
    echo "User [$username] already exists"
else
    echo "User [$username] doesn't exist"
fi

其他回答

根据您的shell实现(例如Busybox vs. grown),[操作符可能会启动一个进程,更改$?

Try

getent passwd $1 > /dev/null 2&>1
RES=$?

if [ $RES -eq 0 ]; then
    echo "yes the user exists"
else
    echo "No, the user does not exist"
fi

我喜欢这个漂亮的单线解决方案

getent passwd username > /dev/null 2&>1 && echo yes || echo no

在脚本中:

#!/bin/bash

if [ "$1" != "" ]; then
        getent passwd $1 > /dev/null 2&>1 && (echo yes; exit 0) || (echo no; exit 2)
else
        echo "missing username"
        exit -1
fi

use:

[mrfish@yoda ~]$ ./u_exists.sh root
yes
[mrfish@yoda ~]$ echo $?
0

[mrfish@yoda ~]$ ./u_exists.sh
missing username
[mrfish@yoda ~]$ echo $?
255

[mrfish@yoda ~]$ ./u_exists.sh aaa
no
[mrfish@indegy ~]$ echo $?
2

到目前为止最简单的解决方案:

if id -u "$user" >/dev/null 2>&1; then
    echo 'user exists'
else
    echo 'user missing'
fi

>/dev/null 2>&1在Bash中可以缩写为&>/dev/null,如果你只想知道一个用户是否不存在:

if ! id -u "$user" >/dev/null 2>&1; then
    echo 'user missing'
fi
#!/bin/bash
read -p "Enter your Login Name: " loginname
home=`grep -w $loginname /etc/passwd | cut -ef:6 -d:`
if [ $home ]
    echo "Exists"
else
    echo "Not Exist"
fi

实际上我无法重现这个问题。问题中编写的脚本工作正常,除了$1为空的情况。

但是,脚本中有一个与stderr重定向相关的问题。虽然存在两种形式&>和>&,但在您的情况下,您希望使用>&。您已经重定向了stdout,这就是&>表单不起作用的原因。你可以用下面的方法验证:

getent /etc/passwd username >/dev/null 2&>1
ls

您将在当前目录中看到一个名为1的文件。你想使用2>&1代替,或者使用这个:

getent /etc/passwd username &>/dev/null

这也将stdout和stderr重定向到/dev/null.

将stderr重定向到/dev/null可能不是一个好主意。当事情出错时,你将不知道为什么。