Find out if user name exists

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

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.


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.

Tags:

Unix

Shell

Bash