tags:

views:

33

answers:

3

Hi,

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,

A: 

use -v option to pass in variable from the shell

awk -v model="$1" '{
  match(model, /foo/)
   .....
}
' dummy
ghostdog74
A: 

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.

Dennis Williamson
my mistake while pasting code here(#!/bin/awk thing). The probelm may be solved if I pass using variable using -v option. But the question remains same why awk is checking comparison opposite way? And if -v is the only option to pass shell variable, then awk shouldn print always " foo is not declared" .right ?
Anil Rana
+1  A: 

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.

schot
Thanks schot !. It works as you said.The dummy just for example here .
Anil Rana