Reputation: 109
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
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
Reputation: 5995
A few things:
$
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.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$
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
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