Search code examples
linuxbashawkredhat

Variable passed to shell script used by awk


I have the following in my bash script (called by another script that passes the variables to it):

psql -qtAX -h "$1" -p "$2" -U "$3" -d "$4" -f "/script/test.sql"

I now want to change this to :

psql -qtAX -h "$1" -p "$2" -U "$3" -d "$4" -f "/script/test.sql" |
awk {print "$2"}'

However, this doesn't give me the right output since the variable $2 that awk is using has defaulted to the value of variable $2 (which is 5432 in the example below) that was passed to the script (instead of getting it from the piped output).

psql -qtAX -h testhost -p 5432 -U user -f "/script/test.sql" |
awk {print "$2"}'

How do I make it so that it gets the $2 value from the piped output instead?


Solution

  • You were close. awk scripts are typically single quoted to avoid shell interpolation (variable replacement) of the awk field variables. In your case, $2 is meaningful to the shell so it has to be escaped with single quotes.

    Try this:

    psql -qtAX -h "$1" -p "$2" -U "$3" -d "$4" -f "/script/test.sql" | awk '{print $2}'