BrT

Musings about technology and other neat stuff

BrT random header image

How to emulate Unix’ getent with MacOSX’s dscl

January 21st, 2008 · 1 Comment

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…

Tags: · · ·

1 response so far ↓

  • 1  yvov // Jan 29, 2009 at 10:42 pm

    #!/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