Marco A
Marco A

Reputation: 109

shell variable usage in awk

I am currently having problems with awk usage of shell variables. Here's my problem, when I run the following:

awk -F: '$1=="marco" {print $7}' /etc/passwd

everything works fine and dandy. However, I want to be able to pass my $user shell variable instead of "marco", so I try the following (after reading about -v flag):

awk -F: -v awkvar=$user '$1=="$awkvar" {print $7}' /etc/passwd

and it doesn't seem to work. Can anyone help me?

Thanks!

Upvotes: 2

Views: 4905

Answers (3)

dAm2K
dAm2K

Reputation: 10329

It's not an awk but a shell problem.

This one would work (if the $user variable is set in your shell environment).

awk -F: '$1=="'"$user"'" {print $7}' /etc/passwd

Upvotes: 0

bonsaiviking
bonsaiviking

Reputation: 5995

A few things:

  1. In awk, a variable is substituted without the $ sigil. $ means "the field at position", so $awkvar means "the field at position value of awkvar". If awkvar=marco, then $awkvar is the same as $"marco", equivalent to $0.
  2. Unlike shell variables, you can't quote awk variables, or else they are treated as strings:

    sh$ awk -v awkvar=foo 'BEGIN{print "awkvar",awkvar}'
    awkvar foo
    sh$ 
    
  3. The standard shell variable containing the username is $USER, not $user

So in conclusion, what you want is this:

awk -F: -v awkvar=$user '$1==awkvar {print $7}' /etc/passwd

Or, using getent:

getent passwd $USER | awk -F: '{print $7}'

Upvotes: 2

Kevin
Kevin

Reputation: 56049

Use quotation marks on the shell side, and don't use $ for awk variables.

awk -F: -v awkvar="$user" '$1==awkvar {print $7}' /etc/passwd

In awk, $ indicates that it's a positional parameter (i.e. a field number), so as it was, it was looking for field "marco", which reduces to $0, the whole line. So it would find any line with only one field.

Upvotes: 3

Related Questions