user76284
user76284

Reputation: 1328

How to retrieve value of first matching attribute in ldapsearch?

If I use the command

ldapsearch -h [HOST] -x -LLL uid=[UID] sn

It will return

dn: [DN]
sn: [SURNAME]
sn;x-role-2: [SURNAME]

for an entry that has multiple values of sn. I have one question in 2 parts:

  1. How can I have ldapsearch return the values of the attributes only, i.e.

    [SURNAME]
    [SURNAME]
    
  2. How can I have ldapsearch return the value of the first matching attribute only, i.e.

    [SURNAME]
    

I know I can do some string manipulation using grep and sed to replicate all of this (and I already have), but I was wondering if there was a more efficient, built-in way to achieve these 2 goals.

Any help would be greatly appreciated!

EDIT: Here is the code I am currently using to accomplish the above:

ldapsearch -h [HOST] -x -LLL uid=[UID] sn | sed 's/[^:]*: //;2q;d'

The sed 's/[^:]*: //;2q;d' first removes the attribute names and then selects the value of the first matching attribute (which is on the second line, since the dn takes up the first line).

Upvotes: 0

Views: 2695

Answers (2)

Bertold Kolics
Bertold Kolics

Reputation: 900

While the answer from @Francois would work (partially), I would also encourage you to look at the LDAP protocol specification, section 4.1.7, which says

The set of attribute values is unordered. Implementations MUST NOT rely upon the ordering being repeatable.

In other words, there is no guarantee which value is going to be the first one. This may be fine if you do not care about which value you are taking. You also need to consider if you care about attributes with tagging options (your example shows that). Should your application take that value instead of the attribute values without the tagging options?

The answer that @Francois provided will not work if you have attribute values that have special characters (the displayed value in that case would be BASE64-encoded and there would two colons after the attribute type - see also RFC 2849).

You may want to consider writing a small script (in Python on Perl) to do what you need without relying on shell magic that may be hard to get right.

Upvotes: 3

Francois
Francois

Reputation: 524

There are some builtins that can indeed help :

cut can split the ouput per column based on a separator (in your case :) head -1 will return the first row of the output.

For example :

  ldapsearch -h [HOST] -x -LLL uid=[UID] sn | cut -d ":" -f 2- 

should only display the attribute value

ldapsearch -h [HOST] -x -LLL uid=[UID] sn | head -1 

should only return the first row of the output

you could also combine them together :

ldapsearch -h [HOST] -x -LLL uid=[UID] sn | head -1 | cut -d ":" -f 2-

http://linux.die.net/man/1/head

http://linux.die.net/man/1/cut

Upvotes: 1

Related Questions