问题描述
我想创建一个脚本来检查用户是否存在.我正在使用以下逻辑:
I want to create a script to check whether a user exists. I am using the logic below:
# getent passwd test > /dev/null 2&>1
# echo $?
0
# getent passwd test1 > /dev/null 2&>1
# echo $?
2
因此,如果用户存在,那么我们就成功了,否则该用户不存在.我在bash脚本中输入了上述命令,如下所示:
So if the user exists, then we have success, else the user does not exist. I have put above command in the bash script as below:
#!/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
现在,无论如何,我的脚本总是说用户存在:
Now, my script always says that the user exists no matter what:
# 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并说用户存在?
Why does the above condition always evaluate to be TRUE and say that the user exists?
我要去哪里错了?
更新:
阅读所有答复后,我在脚本中发现了问题.问题是我重定向getent
输出的方式.因此,我删除了所有重定向内容,并使getent
行看起来像这样:
After reading all the responses, I found the problem in my script. The problem was the way I was redirecting getent
output. So I removed all the redirection stuff and made the getent
line look like this:
getent passwd $user > /dev/null
现在我的脚本运行正常.
Now my script is working fine.
推荐答案
您也可以通过id
命令检查用户.
You can also check user by id
command.
id -u name
为您提供该用户的ID.如果用户不存在,您将获得命令返回值($?
)1
id -u name
gives you the id of that user.if the user doesn't exist, you got command return value ($?
)1
还有其他答案指出:如果只想检查用户是否存在,请直接将if
与id
一起使用,因为if
已经在检查退出代码 .无需摆弄[
,$?
或$()
字符串:
And as other answers pointed out: if all you want is just to check if the user exists, use if
with id
directly, as if
already checks for the exit code. There's no need to fiddle with strings, [
, $?
or $()
:
if id "$1" &>/dev/null; then
echo 'user found'
else
echo 'user not found'
fi
(无需使用-u
,因为您还是要丢弃输出)
(no need to use -u
as you're discarding the output anyway)
此外,如果您将此代码段转换为函数或脚本,建议您也适当设置您的退出代码:
Also, if you turn this snippet into a function or script, I suggest you also set your exit code appropriately:
#!/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`
这篇关于检查用户是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!