CIT 052 Index > Looping and Functions > Passing Command Line Variables to awk

Passing Command Line Variables to awk

Consider the following shell script, which will ask a user for an hour of the day, and then print the month, day, and year if the current hour (as given by date) is greater than or equal to that hour. This script will not work.

#!/bin/bash
echo -n "Enter hour (0-23): "
read hour
date | awk 'BEGIN { FS="[ :]+"; } ; $4 >= hour { print $2, $3, $8 }'

The reason it won’t work is that the variable hour in the shell script has no relation to the variable hour in the awk script. To solve this problem, you need a way to pass a shell variable to an awk script. The solution is the -v option.

#!/bin/bash
echo -n "Enter hour (0-23): "
read hour
date | awk -v awk_hr=$hour 'BEGIN { FS="[ :]+"; } ; $4 >= awk_hr { print $2, $3, $8 }'

The highlighted portion tells awk to set the awk variable awk_hr equal to the current value of the shell variable hour.

While it is possible to use the same name for the shell variable and the awk variable, it’s probably a good idea to name them differently just to make debugging easier.