awk -v: Pass Shell Variables into awk
awk -v name=value sets an awk variable before the program runs, the clean way to pass a shell value in.
Hard-coding a threshold or interpolating a shell variable into the program text is fragile. -v passes the value as data, set before the first line is read.
What it does
awk -v name=value assigns value to the awk variable name before any input is processed (and before BEGIN sees it). It avoids embedding shell expansions in the single-quoted program, so quoting and special characters in the value do not break the script.
Common usage
# pass a numeric threshold from the shell
threshold=80
awk -v t="$threshold" '$2 < t {print "below", $0}' coverage.txt
# pass today's date as a prefix
awk -v d="$(date +%F)" '{print d, $0}' log.txt
# multiple variables
awk -v lo=10 -v hi=20 '$1 >= lo && $1 <= hi' nums.txtUsage
| Form | What it does |
|---|---|
| -v name=value | Set an awk variable before input is read |
| -v t="$shellvar" | Pass a shell value in safely |
| -v a=1 -v b=2 | Set multiple variables |
| var=value file (after program) | Set a variable at that point in the file list |
| ENVIRON["HOME"] | Alternative: read an exported env var directly |
In CI
Pass a gate threshold with -v t="$THRESHOLD" rather than splicing it into the quoted program, which avoids the syntax errors that come from a value containing spaces or quotes. To read an exported environment variable without -v, use ENVIRON["VAR"] inside the program.
Common errors in CI
A -v value undergoes escape processing, so a Windows path or a value with a backslash can be mangled (\t becomes a tab); double the backslashes or use ENVIRON for raw values. Forgetting -v and writing the value inside single quotes leaves the shell variable un-expanded as literal text. A -v assignment with a space and no quotes (-v t=$x where $x has spaces) splits into extra arguments.