When you pass an argument to awk on the command line, it assumes you are giving it a file, so it tries to open it. I don't really get what you were expecting to happen, this is how awk normally behaves.
The reason it works if you remove the { print }
is also quite straightforward. If you remove it, you are left with nothing but a BEGIN{}
block, which is run before any input files are read. Since there's nothing apart from the BEGIN{}
, there is no reason to even try to read a file, and the program exits. This can be easily confirmed with strace
:
$ strace awk 'BEGIN{a=1}{print}' somefile |& grep 'open.*somefile'
openat(AT_FDCWD, "somefile", O_RDONLY) = -1 ENOENT (No such file or directory)
write(2, "cannot open file `somefile' for "..., 66cannot open file `somefile' for reading: No such file or directory) = 66
Compare the above to:
$ strace awk 'BEGIN{a=1}' somefile |& grep 'open.*somefile'
$
Since there's nothing to be done with the file, there is no attempt made to open it.
What I think you are looking for is the foo=bar
format which lets you pass a variable at the command line:
ls -l|./t.awk a=2
Next, change your script to this:
#!/bin/awk -f
BEGIN {
if (!a){
a=5
}
}
{
print a,$0
}
And to illustrate how it works:
$ echo foo | t.awk ## default value
5 foo
$ echo foo | foo.awk a=12 ## value given at launch
12 foo
Alternatively, when running directly from the command line, you can also use the -v
option to do the same thing:
$ awk -v a=12 'BEGIN{print a}'
12