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

现在我的脚本运行正常。


当前回答

下面是检查操作系统分布的脚本,如果不存在则创建User,如果存在则不执行任何操作。

#!/bin/bash

# Detecting OS Ditribution
if [ -f /etc/os-release ]; then
    . /etc/os-release
    OS=$NAME
elif type lsb_release >/dev/null 2>&1; then
OS=$(lsb_release -si)
elif [ -f /etc/lsb-release ]; then
    . /etc/lsb-release
    OS=$DISTRIB_ID
else
    OS=$(uname -s)
fi

 echo "$OS"

 user=$(cat /etc/passwd | egrep -e ansible | awk -F ":" '{ print $1}')

 #Adding User based on The OS Distribution
 if [[ $OS = *"Red Hat"* ]] || [[ $OS = *"Amazon Linux"* ]] || [[ $OS = *"CentOS"*  
]] && [[ "$user" != "ansible" ]];then
 sudo useradd ansible

elif [ "$OS" =  Ubuntu ] && [ "$user" != "ansible" ]; then
sudo adduser --disabled-password --gecos "" ansible
else
  echo "$user is already exist on $OS"
 exit
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

也可以通过id命令查看user。

Id -u name提供该用户的Id。 如果用户不存在,你得到命令返回值($?

正如其他回答所指出的:如果您只想检查用户是否存在,则直接使用if和id,就好像已经检查了退出码一样。没有必要去摆弄琴弦,[,$?(美元):

if id "$1" &>/dev/null; then
    echo 'user found'
else
    echo 'user not found'
fi

(不需要使用-u,因为你正在丢弃输出)

另外,如果你把这个代码片段转换成一个函数或脚本,我建议你也适当地设置退出码:

#!/bin/bash
user_exists(){ id "$1" &>/dev/null; } # silent, it just sets the exit code
if user_exists "$1"; code=$?; then  # use the function, save the code
    echo 'user found'
else
    echo 'user not found' >&2  # error messages should go to stderr
fi
exit $code  # set the exit code, ultimately the same set by `id`

你为什么不直接用呢

grep -c '^username:' /etc/passwd

它将返回1(因为用户有max。如果用户存在,则为1个条目),如果不存在则为0。

用户信息保存在/etc/passwd中,可以使用“grep 'usename' /etc/passwd”查看用户名是否存在。 同时你可以使用“id”shell命令,它会打印用户id和组id,如果用户不存在,它会打印“no such user”消息。

我建议使用id命令,因为它测试有效的用户存在wrt passwd文件条目,这并不一定意味着相同:

if [ `id -u $USER_TO_CHECK 2>/dev/null || echo -1` -ge 0 ]; then 
echo FOUND
fi

备注:0为root uid。