Invoking awk Using the #! Syntax

The “#!” syntax is an alternative syntax for invoking awk from a shell script. It has the advantage of allowing you to specify awk parameters and filenames on the shell-script command line. The “#!” syntax is recognized on modern UNIX systems, but is not typically found in older System V systems. The best way to use this syntax is to put the following line as the first line[6] of the shell script:

#!/bin/awk -f

“#!” is followed by the pathname that locates your version of awk and then the -f option. After this line, you specify the awk script:

#!/bin/awk -f
{ print $1 }

Note that no quotes are necessary around the script. All lines in the file after the first one will be executed as though they were specified in a separate script file.

A few years ago, there was an interesting discussion on the Net about the use of the “#!” syntax that clarified how it works. The discussion was prompted by a 4.2BSD user’s observation that the shell script below fails:

#!/bin/awk
{ print $1 }

while the one below works:

#!/bin/sh
/bin/awk '{ print $1 }'

The two responses that we saw were by Chris Torek and Guy Harris and we will try to summarize their explanation. The first script fails because it passes the filename of the script as the first parameter (argv[1] in C) and awk interprets it as the input file and not the script file. Because no script has been supplied, awk produces a syntax error message. In other words, if the name of the shell script is “myscript,” then ...

Get sed & awk, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.