Question

In following code I am trying to pass shell varibale to awk. But when I try to run it as a.sh foo_bar the output printed is "foo is not declared" and when I run it as a.sh bar_bar the output printed is " foo is declared" . Is there a bug in awk or I am doing something wrong here?

I am using gawk-3.0.3.

#!/bin/awk

model=$1

awk ' {

      match("'$model'", /foo/)
      ismodel=substr("'$model'", RSTART, RLENGTH)
      if (  ismodel != foo ) {
        print  " foo is not declared"
      } else {
        print  " foo is declared"
      }
     }
    ' dummy

dummy is file with single blank line.

Thanks,

Was it helpful?

Solution

This is not a bug, but an error in your code. The problematic line is:

if (  ismodel != foo ) {

Here foo should be "foo". Right now you are comparing with an empty variable. This gives false when you have a match, and true when you have no match. So the problem is not the way you use the shell variables.

But as the other answerers have said, the preferred way of passing arguments to awk is by using the -v switch. This will also work when you decide to put your awk script in a separate file and prevents all kind of quoting issues.

I'm also not sure about your usage of a dummy file. Is this just for the example? Otherwise you should omit the file and put all your code in the BEGIN {} block.

OTHER TIPS

You should use AWK's variable passing instead of complex quoting:

awk -v awkvar=$shellvar 'BEGIN {print awkvar}'

Your script is written as a shell script, but you have an AWK shebang line. You could change that to #!/bin/sh.

use -v option to pass in variable from the shell

awk -v model="$1" '{
  match(model, /foo/)
   .....
}
' dummy
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top