Monday, April 4, 2022

[SOLVED] How to extract the uid value from id on Linux?

Issue

In linux if you type id www-data you get the id.

uid=33(www-data) gid=33(www-data) groups=33(www-data)

Is there a way to extract the value for the uid from this?

I think I could pipe it like this:

id www-data | grep ?

I could also use egrep or sed if its easier, but not sure how to proceed. Similar examples on Stackoverflow deal with the direct extraction of the value via regex. I don't know if the value would be 33. Hence I need to extract it from uid= until (www-data). (unless that is always 33, and I am making my life too difficult). Any suggestion?


Solution

Instead of using a regex, you can use the flags of id (from man id):

-g, --group
       print only the effective group ID
-G, --groups
       print all group IDs
-n, --name
       print a name instead of a number, for -ugG
-r, --real
       print the real ID instead of the effective ID, with -ugG
-u, --user
       print only the effective user ID

This is probably less error prone: if in the future id would change the way it formats the output, the flag will still work.

So use:

$ id -u www-data
33

In general many of these commands offer flags to retrieve parts of the information. Consulting the manpage in general results in a lot of options and only occasionally you find you need something that is not implemented.



Answered By - Willem Van Onsem
Answer Checked By - Marilyn (WPSolving Volunteer)