gawk: Executable Scripts
1
1 1.1.4 Executable 'awk' Programs
1 -------------------------------
1
1 Once you have learned 'awk', you may want to write self-contained 'awk'
1 scripts, using the '#!' script mechanism. You can do this on many
1 systems.(1) For example, you could update the file 'advice' to look
1 like this:
1
1 #! /bin/awk -f
1
1 BEGIN { print "Don't Panic!" }
1
1 After making this file executable (with the 'chmod' utility), simply
1 type 'advice' at the shell and the system arranges to run 'awk' as if
1 you had typed 'awk -f advice':
1
1 $ chmod +x advice
1 $ advice
1 -| Don't Panic!
1
1 (We assume you have the current directory in your shell's search path
1 variable [typically '$PATH']. If not, you may need to type './advice'
1 at the shell.)
1
1 Self-contained 'awk' scripts are useful when you want to write a
1 program that users can invoke without their having to know that the
1 program is written in 'awk'.
1
1 Understanding '#!'
1
1 'awk' is an "interpreted" language. This means that the 'awk'
1 utility reads your program and then processes your data according to the
1 instructions in your program. (This is different from a "compiled"
1 language such as C, where your program is first compiled into machine
1 code that is executed directly by your system's processor.) The 'awk'
1 utility is thus termed an "interpreter". Many modern languages are
1 interpreted.
1
1 The line beginning with '#!' lists the full file name of an
1 interpreter to run and a single optional initial command-line argument
1 to pass to that interpreter. The operating system then runs the
1 interpreter with the given argument and the full argument list of the
1 executed program. The first argument in the list is the full file name
1 of the 'awk' program. The rest of the argument list contains either
1 options to 'awk', or data files, or both. (Note that on many systems
1 'awk' may be found in '/usr/bin' instead of in '/bin'.)
1
1 Some systems limit the length of the interpreter name to 32
1 characters. Often, this can be dealt with by using a symbolic link.
1
1 You should not put more than one argument on the '#!' line after the
1 path to 'awk'. It does not work. The operating system treats the rest
1 of the line as a single argument and passes it to 'awk'. Doing this
1 leads to confusing behavior--most likely a usage diagnostic of some sort
1 from 'awk'.
1
1 Finally, the value of 'ARGV[0]' (⇒Built-in Variables) varies
1 depending upon your operating system. Some systems put 'awk' there,
1 some put the full pathname of 'awk' (such as '/bin/awk'), and some put
1 the name of your script ('advice'). (d.c.) Don't rely on the value of
1 'ARGV[0]' to provide your script name.
1
1 ---------- Footnotes ----------
1
1 (1) The '#!' mechanism works on GNU/Linux systems, BSD-based systems,
1 and commercial Unix systems.
1