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 pa
Using sed:
username="alice"
if [ `sed -n "/^$username/p" /etc/passwd` ]
then
echo "User [$username] already exists"
else
echo "User [$username] doesn't exist"
fi
By far the simplest solution:
if id -u "$user" >/dev/null 2>&1; then
echo 'user exists'
else
echo 'user missing'
fi
The >/dev/null 2>&1
can be shortened to &>/dev/null
in Bash.
Actually I cannot reproduce the problem. The script as written in the question works fine, except for the case where $1 is empty.
However, there is a problem in the script related to redirection of stderr
. Although the two forms &>
and >&
exist, in your case you want to use >&
. You already redirected stdout
, that's why the form &>
does not work. You can easily verify it this way:
getent /etc/passwd username >/dev/null 2&>1
ls
You will see a file named 1
in the current directory. You want to use 2>&1
instead, or use this:
getent /etc/passwd username &>/dev/null
This also redirects stdout
and stderr
to /dev/null
.
Warning Redirecting stderr
to /dev/null
might not be such a good idea. When things go wrong, you will have no clue why.
This is what I ended up doing in a Freeswitch
bash startup script:
# 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
I was using it in that way:
if [ $(getent passwd $user) ] ; then
echo user $user exists
else
echo user $user doesn\'t exists
fi