Celeb Glow
news | March 28, 2026

Evaluate Expression within awk

I want to create a conditional expression string and pass in an awk script. My script is as below...

comm="\$3 == "hello""
awk -F "^T" -v command="${comm}" '
{ if ( command ) { print "hye" } if ( $3 == "hello" ) { print "bye" }
}' test

But the statement "if ( command )" always evaluates to true which is not correct. I want to know the correct way of executing this statement..

On Running...

./test_awk.sh

It returns

hye

Which is not the expected answer.

Test file has following ( just a sample ):

hello^Thye^Tbye

Many thanks in advance

12

2 Answers

If the logical operation is always the same (i.e. in this case ==) and you just want to change the field number and the value against which it is tested, then you can pass them as separate variables e.g.

#!/bin/bash
awk -v field=3 -v value="hello" '
{ if ( $field == value ) { print "hye" } if ( $3 == "hello" ) { print "bye" }
}' test

If you truly want to create a variable awk script, then IMHO a different approach is required, for example using a here document to write the awk script on the fly using the shell to expand your command variable - something like

#!/bin/bash
mycommand="\$3 == \"hello\""
awk -f- test << EOF
{ if ( ${mycommand} ) { print "hye" } if ( \$3 == "hello" ) { print "bye" }
}
EOF
1

Lets trace:

$ cat test
hello^Thye^Tbye
$ awk '{ print ($3 == hello) ? "true" : "false" }' test
true # wrong output
$ awk '{ print ($3 == "hello") ? "true" : "false" }' test
false # correct output

according to trace when we use $3 == hello we get wrong output and when changed to $3 == "hello" including with double quote around the string the output is correct.

So we found the wrong statement and the problem is on comm variable value if you set:

$ comm="\$3 == "hello""

and take echo:

$ echo $comm

you will see the comm variable has below value in it

$3 == hello

so you need double quote around the value then edit your value with this one:

$ comm="\$3 == \"hello\""
$ echo $comm
$3 == "hello"

then go and improve your's. hope this helps.

2

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy