Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

How can I find out, in a shell script, whether a given user name exists on the current system?

/etc/passwd and /etc/shadow are incomplete. Consider OS X's Directory Services, or Linux with Likewise Active Directory integration.

share|improve this question

3 Answers 3

up vote 39 down vote accepted

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

if id -u $1 >/dev/null 2>&1; then
        echo "user exists"
        echo "user does not exist"

Which produces

$ ./userexists root
user exists
$ ./userexists alice
user does not exist
share|improve this answer
You don't need the backquotes here -- just use if id -u "$1" >/dev/null 2>&1; then ... –  Gordon Davisson Sep 17 '11 at 3:03
@Gordon absolutely right of course. Thanks :) –  barbaz Sep 17 '11 at 11:17


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.

share|improve this answer
While Solaris and Linux, and more recently also most BSDs have getent, there is no getent on Mac OS X –  barbaz Sep 17 '11 at 15:37
Indeed, I missed Mac OS/X is missing getent. –  jlliagre Sep 17 '11 at 20:57
Nevertheless it's quite useful on the systems it supports. –  Daniel Beck Sep 19 '11 at 7:52


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.


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.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.