Specify other flags in awk script header

I want to write an awk script file using the #!/bin/awk -f header, but I want this script to always use : as a field separator. But for some reason writing #!/bin.awk -F: -f gives me a syntax error. I also want this script to always run on the same file, so I'd like to hardcode that as well. Basically, what I want to work is this:

#!/bin/awk -F: -f -- /etc/passwd

followed by some awk code


Many systems allow only a single argument in a shebang line, so everything after the space is passed as one argument.

However, you can set FS and even ARGV in your script's BEGIN block, like this:

#!/bin/awk -f              # using the #!/bin/awk -f
BEGIN {
    FS=":"                 # always use : as a field separator
    ARGC=2
    ARGV[1]="/etc/passwd"  # always run on the same file
}
$3==0 {                    # followed by some awk code
    print $1
}

Run it:

$ chmod u+x program.awk
$ ./program.awk
root

Never use a shebang to call awk as that has no worthwhile benefit over simply calling awk within your shell script but robs you of the ability to separate arguments passed to your shell script into values for the shell to process, values for awk to process use -v, values for awk to process using assignments at the end of the script and file names for awk to run on.

Just write:

#!/usr/bin/env bash
awk -F':' '
whatever
' /etc/passwd

so that if you had to you could trivially tweak it to:

#!/usr/bin/env bash
sort "$1" |
awk -F':' -v foo="$2" '
whatever
' - FS="$3" "$4"

or whatever else you need to do to use the arguments passed to your shell script most appropriately and make enhancements (e.g. add initial sorting of the input) without having to change the callers of your script.