brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: getent passwd looks up users the way the system does

Linux
~/tips/tip-linux-getent-passwd-lookup-users

getent passwd jordi

Queries the user database through the Name Service Switch, so it also finds users from LDAP or other sources.

Reading /etc/passwd with cat or grep is the habit, but it only shows local accounts. getent asks the system the way programs do.

getent passwd jordi
getent passwd 1000
getent passwd | wc -l

The first command looks up a user by name, the second by numeric user ID, and the third counts all users the system knows about. The output has the familiar colon-separated fields: name, password placeholder, user ID, group ID, comment, home directory and shell.

The point of getent is that it reads from the Name Service Switch libraries. What it consults follows the configuration in /etc/nsswitch.conf, so a user that comes from a directory service such as LDAP shows up as well, where grep on the local file finds nothing.

It works for other databases too, like getent group and getent hosts example.com, which resolves a name like programs do instead of asking DNS directly.

The exit status is useful in scripts: it is 0 when found and 2 when the key could not be found.

The caveat is about listing everything. Without a key, getent enumerates the database, and some sources do not support that or only return part of it, so the count of users on a machine with a directory service can be lower than you expect. Looking up one name is the reliable way.

Further reading: getent(1) manual page

More Linux tips a2query -m rewrite renice -n 10 -p 4242 cat config.yml | xsel -ib xvfb-run -a your-program --some-flag dpkg --get-selections > packages.txt All Linux tips (261) All topics

Link