How to emulate Unix' getent with MacOSX's dscl

The Unix getent command does not exist in OSX. Starting from 10.5 (Leopard), the administrative databases have changed from Netinfo to DirectoryService, and the main tool for looking things in DS is dscl (see also this article at afp548.com).

For example, to query a user by UID with getent, you would run:

getent passwd <uid>

With dscl, you could do something like this:

dscl . -search /Users UniqueID <uid>

In both cases, you then need to parse the output to get the username. The output of getent is standard /etc/passwd format, something like this:

zamboni:x:1005:1005:Diego Zamboni,,,:/home/zamboni:/bin/bash

This is very easy to parse (using awk, for example) and gives you the full record at once.

dscl only provides the field you searched for, something like this:

zamboni              UniqueID = (
    501
)

So if you want to get the full record, you would need to get the username and then query for it, like this:

dscl . -read /Users/zamboni

The output is harder to parse, in “keyword: value” form, but with many multiline values. You can also use the -plist option to get it in Apple’s plist format, which could be easier to parse.

I guess one could write a wrapper around dscl that provides output in getent format…

Advertisements

One response to “How to emulate Unix' getent with MacOSX's dscl

  1. #!/bin/bash

    if [ -z $1 ];
    then
    echo "You must specify an user"
    exit 1
    else
    echo `dscl . -read /Users/$1 RecordName | sed 's/RecordName: //g'`:*:`dscl . -read /Users/$1 UniqueID | sed 's/UniqueID: //g'`:`dscl . -read /Users/$1 PrimaryGroupID | sed 's/PrimaryGroupID: //g'`:`dscl . -read /Users/$1 RealName | sed -e 's/RealName://g' -e 's/^ //g' | awk '{printf("%s", $0 (NR==1 ? "" : ""))}'`:/Users/$1:`dscl . -read /Users/$1 UserShell | sed 's/UserShell: //g'`
    fi

    exit 0

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s