shell variable inside awk without -v option it is working

I noticed that a shell script variable can be used inside an awk script like this:

awk 'BEGIN{print "'$var'" }'

Can anyone tell me how to change the value of var inside awk while retaining the value outside of awk?

Similarly to accessing a variable of shell script inside awk, can we access shell array inside awk? If so, how?


It is impossible; the only variants you have:

  • use command substitution and write output of awk to the variable;
  • write data to file and then read from the outer shell;
  • produce shell output and then execute it with eval.


Command substitution, one variable:

$ export A=10
$ A=$(awk 'END {print 2*ENVIRON["A"]}' < /dev/null)
$ echo $A

Here you multiple A by two and write the result of multiplication back.

eval; two variables:

$ A=10
$ B=10
$ eval $(awk 'END {print "A="2*ENVIRON["A"]"; B="2*ENVIRON["B"]}' < /dev/null)
$ echo $A
$ echo $B
$ awk 'END {print "A="2*ENVIRON["A"]"; B="2*ENVIRON["B"]}' < /dev/null
A=40; B=40

It uses a file intermediary, but it does work:

var="hello world"
cat > /tmp/my_script.awk.$$ <<EOF
BEGIN { print \"$var\" }
awk /tmp/my_script.awk.$$
rm -f /tmp/my_script.awk.$$

This uses the here document feature of the shell, Check your shell manual for the rules about interpolation within a here document.

Need Your Help

how to increment a gridview cell value on same record

c# gridview datagridview increment

i have 7 columns (code, sales man, description, size, QTY, price, amount).

Digest Auth in Spring Security with REST and Javaconfig

java spring spring-security digest-authentication spring-rest

I am having issues setting up digest authentication with spring security: