Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'd like to grep /etc/password for a username and return the last two digits of a user-id number as the return code.

This is because I have an application whose main way of interacting with other programs is something like integer_variable = run("some command") which picks up the byte value of the exit code of the command.

I can do this using something like the following command

perl -n -e 'exit $1%100 if /^username:x:(\d+):/' /etc/passwd

Is there an equivalent using awk or some other standard utility?

share|improve this question
    
@terdon: I agree it's unusual, but I have several Unix systems that lack it. For example, I have Xenix in a box somewhere. Some minimal Linux distros omitted it too. – RedGrittyBrick Dec 4 '13 at 15:31
    
Really? Actual Linux distros? Not embedded or busybox based systems? Wow, fair enough then, I stand corrected. – terdon Dec 4 '13 at 15:33
up vote 2 down vote accepted
id=$( getent passwd $username | cut -d: -f3 | sed 's/.*\(..\)$/\1/' )

with awk

awk -v u=$username -F: '$1 == u {exit $3%100}' /etc/passwd
share|improve this answer

What do you mean "some other standard utility"? If you want a shell script to return arbitrary exit statuses, you can pass any value to the shell builtin exit:

exit `awk -F: $USER '{print $2}' /etc/passwd`

(or just exit 35, etc.)

That lets you transform output into an exit status, even for programs that do not have an exit operation like perl and awk do. But keep in mind that the Unix convention is for successful programs to return 0, so you'll get some weird behavior if you run your special program from the commandline (etc.)

share|improve this answer
    
By standard utility I meant anything that is commonly available from the usual shells (sh, bash, ksh, csh ...) on Linux and Unix (both modern and ancient). On some Unix systems perl may not be installed as standard. Thanks for the tip re exit. – RedGrittyBrick Dec 4 '13 at 14:49
    
I see; I was counting perl among the standard options, hence the "why not just use perl" confusion. – alexis Dec 4 '13 at 14:52

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.