brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: awk -v passes a shell variable into an awk program

Shell
~/tips/tip-awk-v-assign-variable

df -P | awk -v max="$limit" 'NR > 1 && $5+0 > max {print $6, $5}'

Hands a value from your shell script to awk without breaking the quoting.

The moment a shell script needs a value inside an awk program, the quoting fight starts. You close the single quotes, stick "$limit" in, open them again, and hope nobody ever puts a space or a quote in that variable.

-v skips all of that. It sets an awk variable before the program starts, even before a BEGIN block runs:

limit=90
df -P | awk -v max="$limit" 'NR > 1 && $5+0 > max {print $6, $5}'

This prints every mount point that is more than 90 percent full. The awk program stays in single quotes, untouched, and the shell value arrives as max. The $5+0 turns 93% into the number 93, and NR > 1 skips the header line. You can give -v as often as you need, one variable each time, and it has to come before the program text.

The caveat is backslashes. awk treats the value like a string in a program, so escape sequences get processed: -v p='C:\temp' turns the \t into a tab. For values that may contain backslashes, like Windows paths or regexes, export the variable and read it through ENVIRON instead:

P='C:\temp' awk 'BEGIN {print ENVIRON["P"]}'

That prints the text exactly as it was. My advice is to use -v by default and ENVIRON as soon as a backslash might show up.

Further reading: gawk manual: assigning variables on the command line, gawk(1) manual page

More Shell tips zmv -n '(*).log' '$1.txt' zoxide query -ls project f=$(mktemp --suffix=.json) shopt globskipdots echo $EPOCHSECONDS All Shell tips (78) All topics

Link