I want to display all the usernames in the /etc/passwd file.
I know I can use the following command to achieve this:
$ cut -d: -f1 /etc/passwd
Is there another way to achieve this?
Note: I'll politely ask that the RHCE-level and RHCA-level folks to sit this one out!
Sure,
awk -F ':' ' { print $1 } ' /etc/passwd
Or this specific that I often use in order to display all the "normal" users created on a system
awk -F ':' ' $3 >= 1000 { print $1 } ' /etc/passwd
Thanks for including that command to dsplay all regular (or as you say "normal") users.
That brings up another question - would system users be displayed using your 2nd command?
You can also use this command, which I find cleaner and more reliable:
getent passwd | cut -d: -f1
It works just like reading /etc/passwd, but it also includes users from other sources like LDAP or NIS if your system uses them. Basically, it's a safer and more flexible option.
And if you only want to list the "normal" users (not system accounts), this does the trick:
getent passwd | awk -F: '$3 >= 1000 && $3 < 60000 { print $1 }'
For more complex use cases, we can easily extend this with Perl, Python, or even Bash scripting to handle custom logic.
I'll accept your comment about your "getent passwd | cut -d: f1" being a more flexible option. What makes it a "safer" option?
I like the command that eliminates the display of system accounts.
Aah, I totally missed your question earlier >> great catch!
getent passwd is safer because it uses the system’s configured sources (like LDAP, NIS, etc.) via nsswitch.conf, not just /etc/passwd. So you get a complete and consistent view of users, especially in enterprise or hybrid environments.
Glad the system-user filter helped too!
@Trevor as per your command - I am ducking this one out :)D
Chetan, I made that request only because this question is the equivalent of a preseason football game - during preseason, I don't wish to risk injury to the veterans on the team like yourself : - )
Red Hat
Learning Community
A collaborative learning environment, enabling open source skill development.