Check Whether a User Exists

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

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

Why does the above condition always evaluate to be TRUE and say that the user exists?

Where am I going wrong?

UPDATE:

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.


Solution 1:

You can also check user by id command.

id -u name gives you the id of that user. if the user doesn't exist, you got command return value ($?)1

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

(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`

Solution 2:

Why don't you simply use

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

It will return 1 (since a user has max. 1 entry) if the user exists and 0 if it doesn't.