Find out if user name exists

Solution 1:

One of the most basic tools to be used for that is probably id.

#!/bin/bash
if id "$1" >/dev/null 2>&1; then
        echo "user exists"
else
        echo "user does not exist"
fi

Which produces

$ ./userexists root
user exists
$ ./userexists alice
user does not exist
$ ./userexists
user does not exist

Solution 2:

getent

This command is designed to gather entries for the databases that can be backed by /etc files and various remote services like LDAP, AD, NIS/Yellow Pages, DNS and the likes.

To figure out if a username is known by one of the password naming services, simply run:

getent passwd username

This works also with group, hosts and others, depending on the OS and implementation.

Solution 3:

finger

Parse the output of finger -m <username>. No error code if no user was found, unfortunately, but if not found, error output will be written. No drawbacks so far.

finger -ms <username> 2>&1 1>/dev/null | wc -l

Will print 0 if user is found (because there's no error output), larger numbers otherwise.

chown

Run (as any user, surprisingly):

T=$( mktemp -t foo.XXX ) ; chown <username> $T

If it fails as root, the account name is invalid.

If it fails as non-root user, parse the possibly localized output for Operation not permitted or invalid user (or equivalents). Set LANG beforehand to do this reliably.

Solution 4:

I would say that you would want to rely on /etc/passwd and similar (e.g. /etc/shadow for Shadow-based systems; on an off-topic side-note, some similar systems might use /etc/master.passwd or other such files).

The /etc/passwd is typically treated as the absolute authoritative decision on whether a user exists or not. If you use any of the other methods described on this page, and if those other methods point to an existing user but /etc/passwd does not, then I would say that the user does not properly exist on the system, by definition of the most common standard that software would likely rely on.

That said, I'll throw in another way to add to the mix of some other options that could be used.

ls -l /home | grep ^customUserName$<BR> echo $?

Clearly, replace "customuserName" with the name of the user you want to check for. Replace /home with /users if that is what your system uses. This might not find all users in /etc/passwd if no home directory was made for the particular user, which could occur if you simply imported users (that is, lines of text into /etc/passwd) and if home directories don't get made unless/until a person logs in.