GNU awk wants to treat arguments as paths

gawk

I have this minimal awk example:

#!/usr/bin/awk -f
BEGIN {
  if (ARGC>1)
    a=ARGV[1]
  else
    a=5
}

{
  print
}

Calling it with ls -l|./t.awk, results in:

$ ls -l|./t.awk 2
awk: ./t.awk:4: fatal: cannot open file `2' for reading (No such file or directory)

When calling it without arguments (ls -l|./t.awk), there is no problem.

Thus, my first problem is that instead of a simple string equality check, somehow it tries to read in the file named "2".

The second surprising thing is that removing the second block makes it work as it should! (Giving empty output.)

#!/usr/bin/awk -f
BEGIN {
  if (ARGC>1)
    a=ARGV[1]
  else
    a=5
}

What is the cause?

Best Answer

Though awk presents you with the arguments, it is up to you to manipulate them into what you finally wish to have. Eg, just set the arg empty:

if (ARGC>1) {a=ARGV[1]; ARGV[1]=""}
else a=5

Otherwise, the args have their normal function, which for non-options is to be input filenames. So awk will try to read file "2" and run the body of the script on it.

Related Question