Okay, let's look at the common and recommended ways to pass multiple variables from the Command Line Interface (CLI) to an awk script.
The Best Method: Using the -v Option (Recommended)
This is the cleanest, safest, and most standard way. You use the -v option for each variable you want to define before the awk script itself.
Syntax:
awk -v awk_var1="shell_value1" -v awk_var2="shell_value2" ... 'awk script' input_file(s)
-v awk_varN="shell_valueN": This assigns the string shell_valueN to the awk variable awk_varN.
- Important:
- The assignment happens before
awk starts processing the input file, even before the BEGIN block executes.
- Quote the shell values (
"shell_valueN") if they contain spaces or special shell characters. This prevents the shell from interpreting them before passing them to awk.
- Use single quotes (
'awk script') around your awk script to prevent the shell from expanding things like $1, $2, or other shell variables within the script itself.
Example:
Let's say you have a file data.txt:
apple 10 red
banana 5 yellow
orange 8 orange
grape 20 purple
apple 15 green
And you want to find lines where the first field matches a target fruit and the second field is greater than a minimum quantity, both provided from the shell:
#!/bin/bash
target_fruit="apple"
min_quantity=12
filename="data.txt"
echo "Searching for '$target_fruit' with quantity > $min_quantity in '$filename'"
# Pass shell variables to awk using -v
awk -v fruit="$target_fruit" \
-v min="$min_quantity" \
'BEGIN { printf("AWK: Target Fruit: %s, Minimum Quantity: %d\\n", fruit, min) }
$1 == fruit && $2 > min {
print "Found:", $0
}' "$filename"
echo "---"
# Example changing variables
target_fruit="grape"
min_quantity=10
awk -v f="$target_fruit" -v m="$min_quantity" \
'$1 == f && $2 > m { print $0 }' "$filename"
Output:
Searching for 'apple' with quantity > 12 in 'data.txt'
AWK: Target Fruit: apple, Minimum Quantity: 12
Found: apple 15 green
---
grape 20 purple
Alternative Method 1: Using Environment Variables (ENVIRON)
You can export shell variables and access them within awk using the special ENVIRON associative array.
Syntax:
export SHELL_VAR1="value1"
export SHELL_VAR2="value2"
awk 'awk script using ENVIRON["SHELL_VAR1"] and ENVIRON["SHELL_VAR2"]' input_file(s)
# Unset them if you don't need them exported anymore
unset SHELL_VAR1
unset SHELL_VAR2
Example:
#!/bin/bash
export TARGET_FRUIT="orange"
export MIN_QUANTITY=5
filename="data.txt"
echo "Searching using ENVIRON: '$TARGET_FRUIT' with quantity > $MIN_QUANTITY"
awk 'BEGIN { printf("AWK ENV: Target Fruit: %s, Minimum Quantity: %s\\n", ENVIRON["TARGET_FRUIT"], ENVIRON["MIN_QUANTITY"]) }
# Note: ENVIRON values are strings, so compare numerically if needed
$1 == ENVIRON["TARGET_FRUIT"] && $2 > (ENVIRON["MIN_QUANTITY"] + 0) {
print "Found:", $0
}' "$filename"
unset TARGET_FRUIT
unset MIN_QUANTITY
Output:
Searching using ENVIRON: 'orange' with quantity > 5
AWK ENV: Target Fruit: orange, Minimum Quantity: 5
Found: orange 8 orange
Pros: Useful if variables are already in the environment.
Cons: Modifies the shell environment (export), slightly more verbose in awk (ENVIRON["VAR"]), values are always strings (may need explicit conversion for numeric comparisons like +0).
Alternative Method 2: Direct Shell Expansion (Generally Discouraged)
You can try to splice shell variable values directly into the awk script string. This is strongly discouraged because it's:
- Error-prone: Quoting becomes extremely complex and hard to get right, especially if the variable values contain spaces, quotes, or other special characters.
- Insecure: If the variable content comes from an untrusted source, this method opens you up to code injection vulnerabilities. A malicious value could contain
awk commands that get executed.
Example (Do NOT use this for complex or untrusted input):
#!/bin/bash
# --- DANGEROUS EXAMPLE ---
target_fruit="banana"
min_quantity=3 # Simple numeric value, less risky but still bad practice
filename="data.txt"
echo "Searching via direct expansion (BAD PRACTICE): '$target_fruit', > $min_quantity"
# Very fragile quoting: close single quote, use double quotes for shell var, reopen single quote
awk '$1 == "'"$target_fruit"'" && $2 > '"$min_quantity"' { print "Found:", $0 }' "$filename"
# --- END DANGEROUS EXAMPLE ---
Output:
Searching via direct expansion (BAD PRACTICE): 'banana', > 3
Found: banana 5 yellow
Why it's bad: Imagine target_fruit="apple ; { print \"hacked\" }" - this could break your script or execute unwanted code.
Conclusion:
Always prefer the -v option for passing multiple variables from the shell to awk. It's the safest, clearest, and most standard approach. Use environment variables (ENVIRON) if it fits your workflow, but be mindful of the implications. Avoid direct shell expansion into the awk script string.