Ask Dave Taylor: Tech and Business

Sunday

How do I extract users from /etc/password in a shell script?

I am working on a script where I would like to grab the usernames out of the passwd file for a defined range of UIDs. For example I would like to pull the usernames for all users in /etc/passwd that are in the range of 5000-5999. Can you help?

While this task might initially sound daunting, it's actually quite easy to accomplish by using either Perl or awk. My preference is awk, simply because I know that it's included in every single version of Unix or Linux, however old or obsolete, so let's look at how that'd help us here.

First off, I'm going to assume that the only thing you need is the username itself, not any of the other fields in the password file. I think that's safe!

A typical entry in the /etc/passwd file looks like this:

root:*:0:0:System Administrator:/var/root:/bin/sh


In order, the fields, separated by colons, are...