Aug 262000

Want a list of users on your box?

If you ever want a list of users on your system, use this little script:
cat /etc/passwd | cut -d: -f1 | grep -v \#

The cut command selects portions of a file.  We use ":" as the delimiting character.  And we want only the first field.  The grep eliminates lines with # in them, which normally appear at the start of the password file.

Exercises for the interested and motivated:

  • try the above command without the grep
  • remove the \ before the #
  • try -f5 instead of -f1.

Hope that helps.

My thanks to halflife for the original idea and to pal for adding the grep.

  7 Responses to “Want a list of users on your box?”

  1. (written by Peter Chiu but posted by Dan Langille)

    another solution is:-

    awk -F: ‘! /^#/ { print $1 }’ /etc/passwd

    -F: use colon as separator
    ! /^#/ not beginning with a #
    print $1 print first field

  2. (written by Todor Zahariev, posted by Dan Langille)

    I have suggestion for printing user:

    cat /etc/passwd | cut -d: -f1 | grep -v \#

    change to:

    grep -v \# /etc/passwd | cut -d: -f1

    1. save 1 pipe and 1 cat execution.
    2. move thru the pipe less data (removed lines with #)

  3. (written by Kanji T Bates, posted by Dan Langille)

    Why use three commands, when one will do the same job? 🙂

    awk -F: ‘$1 !~ /#/ { print $1 }’ /etc/passwd

    perl -le ‘print while $_ = getpwent’

  4. (posted by Dan Langille)

    I think awk has a reasonable learning curve, especially to new users, so its good to see examples of awk. Especially since this is where awk shines.

    Here is the awk way:

    ( print the first field of any line that does not have a pound sign in it. )
    awk -F: ‘!/#/ { print $1 }’ /etc/passwd

    (print lines where a comment does not exist in field 1)
    awk -F: ‘$1 !~ /#/ { print $1 }’ /etc/passwd

  5. (posted by Dan Langille)

    awk -F: ‘{ print $1 }’ /etc/passwd

  6. (posted by Dan Langille)

    Your one-line shell script:

    cat /etc/passwd | cut -d: -f1 | grep -v \#

    should be rewritten as:

    cut -d: -f1 /etc/passwd | grep -v \#

    or, better yet, as a Perl script:

    perl -le ‘print while $_=getpwent’

  7. (posted by Dan Langille)

    An alternative would be to use the following perl one-liner…

    perl -pe ‘s/(\w+).*/$1/’ /etc/passwd

    which is that bit simpler (OK, it -IS- if you know perl 🙂