31

I'm really new with bash, but it's one of the subjects on school. One of the exercises was:

Give the line number of the file "/etc/passwd" where the information about your own login is.

Suppose USERNAME is my own login ID, I was able to do it perfectly in this way:

 cat /etc/passwd -n | grep USERNAME | cut -f1

Which simply gave the line number required (there may be a more optimised way). I wondered however, if there was a way to make the command more general so that it uses the output of whoami to represent the grep pattern, without scripting or using a variable. In other words, to keep it an easy-to-read one-line command, like so:

 cat /etc/passwd -n | grep (whoami) | cut -f1

Sorry if this is a really noob question.

3 Answers 3

39
cat /etc/passwd -n | grep `whoami` | cut -f1 

Surrounding a command in ` marks makes it execute the command and send the output into the command it's wrapped in.

1
  • 1
    Without anchoring, this can produce false matches if your login name matches elsewhere on the line. I used to have a short login name on a local system which happened to match (a substring of) "System Operator" so some stupid software thought I was root when I wasn't.
    – tripleee
    Nov 17, 2014 at 11:58
14

You can do this with a single awk invocation:

awk -v me=$(whoami) -F: '$1==me{print NR}' /etc/passwd

In more detail:

  • the -v creates an awk variable called me and populates it with your user name.
  • the -F sets the field separator to : as befits the password file.
  • the $1==me only selects lines where the first field matches your user name.
  • the print outputs the record number (line).
2
  • thanks for the great explanation, but for now it seems to advanced for me to build up commands like that myself :)
    – MarioDS
    Apr 23, 2012 at 13:12
  • 8
    @Mario: the sooner you start learning, the sooner you'll be able to charge exorbitant rates for your development services :-)
    – paxdiablo
    Apr 23, 2012 at 13:13
12

Check command substitution in the bash man page.

You can you back ticks `` or $() , and personally I prefer the latter.

So for your question:

grep -n -e $(whoami) /etc/passwd | cut -f1 -d :

will substitute the output of whoami as the argument for the -e flag of the grep command and the output of the whole command will be line number in /etc/passwd of the running user.

2
  • +1 because it works, but Lynn's answer is more clear to read (at least to a beginner like me :)) but I like that you pointed out I should use the -n switch of grep to make it shorter.
    – MarioDS
    Apr 23, 2012 at 13:01
  • 4
    +1, I prefer the $() construct as well, simply because it's so much easier to nest.
    – paxdiablo
    Apr 23, 2012 at 13:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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