Search code examples
shellunixawkgawkshebang

How to use multiple arguments for awk with a shebang (i.e. #!)?


I'd like to execute an gawk script with --re-interval using a shebang. The "naive" approach of

#!/usr/bin/gawk --re-interval -f
... awk script goes here

does not work, since gawk is called with the first argument "--re-interval -f" (not splitted around the whitespace), which it does not understand. Is there a workaround for that?

Of course you can either not call gawk directly but wrap it into a shell script that splits the first argument, or make a shell script that then calls gawk and put the script into another file, but I was wondering if there was some way to do this within one file.

The behaviour of shebang lines differs from system to system - at least in Cygwin it does not split the arguments by whitespaces. I just care about how to do it on a system that behaves like that; the script is not meant to be portable.


Solution

  • This seems to work for me with (g)awk.

    #!/bin/sh
    arbitrary_long_name==0 "exec" "/usr/bin/gawk" "--re-interval" "-f" "$0" "$@"
    
    
    # The real awk program starts here
    { print $0 }
    

    Note the #! runs /bin/sh, so this script is first interpreted as a shell script.

    At first, I simply tried "exec" "/usr/bin/gawk" "--re-interval" "-f" "$0" "$@", but awk treated that as a command and printed out every line of input unconditionally. That is why I put in the arbitrary_long_name==0 - it's supposed to fail all the time. You could replace it with some gibberish string. Basically, I was looking for a false-condition in awk that would not adversely affect the shell script.

    In the shell script, the arbitrary_long_name==0 defines a variable called arbitrary_long_name and sets it equal to =0.