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

现在我的脚本运行正常。


当前回答

没有必要显式地检查退出代码。试一试

if getent passwd $1 > /dev/null 2>&1; then
    echo "yes the user exists"
else
    echo "No, the user does not exist"
fi

如果这不起作用,则说明您的geent有问题,或者您定义的用户比您想象的要多。

其他回答

使用sed:

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

这就是我最终在Freeswitch bash启动脚本中所做的:

# Check if user exists
if ! id -u $FS_USER > /dev/null 2>&1; then
    echo "The user does not exist; execute below commands to crate and try again:"
    echo "  root@sh1:~# adduser --home /usr/local/freeswitch/ --shell /bin/false --no-create-home --ingroup daemon --disabled-password --disabled-login $FS_USER"
    echo "  ..."
    echo "  root@sh1:~# chown freeswitch:daemon /usr/local/freeswitch/ -R"
    exit 1
fi

检查Linux用户是否存在的脚本

脚本检查用户是否存在

#! /bin/bash
USER_NAME=bakul
cat /etc/passwd | grep ${USER_NAME} >/dev/null 2>&1
if [ $? -eq 0 ] ; then
    echo "User Exists"
else
    echo "User Not Found"
fi

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

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
echo "$PASSWORD" | su -c "cd /" "$USER"
if [ "$?" = "0" ];then
 echo "OK"
else
 echo "Error"
fi