Page Actions
Wiki Actions
User Actions
Submit This Story

Lazy Interviewer: Extract System Users

Helped to perform some interview for my corp though I myself is a rookie. The questionaire provided is rather straight-forward. I am to ask about basic knowledge on *Nix and shells as well as scripting languages.

The Question

One of the question is, how to produce a user list of *Nix system. This is a simple /etc/passwd field extraction. And since I'm lazy I just bundle all the skill points into one:

So here comes the so-called standard anwser provided, using awk:

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

And lazy as I myself just think of an perl solution, as an Perl interview question:

perl -F: -lane 'print $F[0]' /etc/passwd

Slow but handy sed:

sed 's/\(\):.*/\1/g' /etc/passwd

And why perl/awk since we can do it in shell and simpler coreutils, like cut?

while read input; do login="$(echo $input | cut -d: -f1)" ; echo $login ; done < /etc/passwd

edit:

Oop…My silliness… just cut and no shell wrapping needed:
cut -d: -f1 /etc/passwd

Blah, why bother cut when pure shell(ksh, bash, zsh) it self can do it:

while read input; do echo ${input%%:*}; done < /etc/passwd

Somewhat dirty Shell Internal Field Seperator(IFS) trick:

IFS=:; while read username others; do echo ${username}; done < /etc/passwd; IFS= ;

Don't forget to set IFS back…

And… I don't know perl well, Python is my shield against those interviewer questioning my ignorance of perl …I used to state to an interviewer:

“For what perl does, I can do simple things in awk easier, complicated thing in Python nicer.”
python -c 'print "\n".join(line.split(":",1)[0] for line in open("/etc/passwd"))'

Haah. Evil one-liner is do-able in Python! Cultist!

There comes a issue though. Some system dev or some SA, dunno why, is bored enough to put comments in /etc/passwd! Perl do this easy:

perl -F: -lane 'print $F[0] if !/^#/' /etc/passwd

While a piece of cake for awk:

awk -F ':' '$1 !~ /^#/ { print $1 }' /etc/passwd

As a Perl dummer and Python cultist:

python -c 'print "\n".join((line.split(":",1)[0] for line in open("/etc/passwd") if not line.startswith("#")))'

Kindda long but clear. YAY! One question for all interview topic.

Guys that can produce more than one way are cool. And anyone who can provide some more is the Mr. Gadget!

Discussion

Enter your comment
 
 
blog/2010/10/etc_passwd.txt · Last modified: 2010/10/10 20:55 by MeaCulpa     Back to top
Recent changes RSS feed Creative Commons License Powered by PHP Driven by DokuWiki