Check Whether a User Exists

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`

Leave a Comment