You can probably use either of these:
awk -F: "\$1 ~ /$username/ { print \"Username:\t\t\t\", \$1}"
awk -F: "\$1 == \"$username\" { print \"Username:\t\t\t\", \$1}"
where the backslash before $1
protects the $
from the shell, and the backslash before the double quotes protects them from the shell. There are times when it is worth using -f awk.script
; it is not clear that this is one of them.
The difference between the ~
and the ==
notation is that the ~
variant matches using a regex. The version using the ==
goes for simple equality, of course. Using a match means you could have username='^(root|daemon|bin|sys)$'
and you'd get the entries for the four named users in a single invocation of the script. The downside is that if you specify just root
, you might get multiple entries (for example, on my Mac, I get both root
and _cmvsroot
listed).
These scripts use double quotes so that the username can be embedded into the script from the command line. However, as correctly pointed out by Ed Morton in his comment, this leads to a surfeit of backslashes in the script. I generally use single quotes around scripts (despite not doing so in the first edition of this answer).
awk -F: '$1 ~ /'"$username"'/ { print "Username:\t\t\t", $1}'
awk -F: '$1 == "'"$username"'" { print "Username:\t\t\t", $1}'
Those quote sequences are subtle; it is better to avoid them. You can do that by specifying initial values for variables on the command line with -v varname="value"
notation. Therefore, you could also use:
awk -F: -v username="$username" \
"\$1 == username { print \"Username:\t\t\t\", \$1}" /etc/passwd
or, better, since it uses single quotes around the script:
awk -F: -v username="$username" \
'$1 == username { print "Username:\t\t\t", $1}' /etc/passwd
This sets the awk
variable username
from the shell variable $username
. This variation can be used with a file:
awk -F: -v username="$username" -f awk.script /etc/passwd
with awk.script
containing:
$1 == username { print "Username\t\t\t", $1 }