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.

link|improve this question

1  
I'd appreciate if the down voter would leave a comment telling me what's wrong with this post. – Daniel Beck Oct 1 '11 at 14:48
feedback

3 Answers

up vote 11 down vote accepted

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

#!/bin/bash
if id -u $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
link|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
feedback

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.

link|improve this answer
feedback

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.

link|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
feedback

Your Answer

 
or
required, but never shown

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