sea
1
Heyas
Recently i wanted to help someone with an awk script, but the end-script didnt work as expected.
He wanted, if HOME was empty, to get the HOME of the current USER from /etc/passwd.
At first i tried hardcoded with root:
awk -F: '/^root/ {print $6}' /etc/passwd
As that worked, i've added a variable, for the changeable 'current user'.
awk -v U=$(whoami) -F: '/^U/ {print $6}' /etc/passwd
But this didnt want to work, so in the end i had to:
cmd="awk -F: '/^$(whoami)/ {print \$6}' /etc/passwd"
eval $cmd
Why is my 2nd code not working? (just returns empty)
Any (better) ideas?
Thank you
RudiC
2
As /.../
is a regex constant, it would try to match the literal string "U" at the begin-of-line. Try $0 ~ "^"U
.
1 Like
cjcox
3
awk -v U=$(whoami) -F: '"/^" U "/" {print $6}' /etc/passwd
1 Like
Hello sea,
Following may also be an option on same.
awk -v U=$(whoami) -F: '($1 == U) {print $6}' /etc/passwd
Actually in my server directories are having pretty similar names as users have so I have done with by directly comparing the 1st column itself.
Thanks,
R. Singh
1 Like
Hi, I do not think this will work. That evaluates to:
awk -F: '"/^username/"{print $6}' /etc/passwd
Which means if the string "/^username/"
is true (i.e. non-empty) then print $6
So this always evaluates to true and it will print field 6 on every line..