I need to find a user, and the command should exit with a non-zero return code if the user is not in the system. We can do this in bash, but I need this as a line command, not a bash script. Is that possible?


1 Answer 1


A good way of testing whether a user exists on a system is by using getent. The getent utility can return various pieces of information from various "databases", for example, the passwd "database", the group "database", and, on some systems, you can even ask getent to list the available login shells.

To test whether a user, testuser, is in the system, ask getent for the passwd entry for that user:

getent passwd testuser

If this succeeds, you will get a single passwd entry as output and a zero exit status from getent. If it fails, you will get no output and a non-zero exit status. I believe that this is the command that you are asking for.

We may discard whatever output the utility generates and use it in an if statement, like so:


if getent passwd "$theuser" >/dev/null
    printf 'The user "%s" exists\n' "$theuser"
    printf 'The user "%s" does not exist\n' "$theuser"

You could instead, of course, parse the /etc/passwd file directly with some grep command, but that is error-prone (in comparison to using getent as shown above) and also would not work correctly on systems where some form of directory service is in use.

  • 1
    cut -d: -f1 /etc/passwd | grep -Fxq username is also not all too bad^^ But getent is surely better.
    – pLumo
    May 7, 2022 at 18:55
  • Thanks Kusalananda♦ never heard about getent,thanks for sharing...
    – Renga
    May 8, 2022 at 2:49

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .