For Programmers: Free Programming Magazines  


Home > Archive > AWK > January 2005 > correctly starting awk scripts









You are viewing an archived Text-only version of the thread. To view this thread in it's original format and/or if you want to reply to this thread please [click here]

 

Author correctly starting awk scripts
Marc Vertes

2005-01-04, 8:55 am

Hi,

I wanted to process options in my awk scripts starting by:

#!/usr/bin/awk -f
BEGIN {
for (i = 1; i < ARGC; i++) print ARGV[i]
exit
}

I found that it was impossible to pass arguments starting with "-",
as they were eaten by awk itself rather than my script.
And yes, I know how to use "--".

Here is now my solution:

#!/bin/sh
#
# The following code line is interpreted both by awk and /bin/sh.
# In sh, it's a command line that restarts awk to interpret this script.
# In awk, it's a combined pattern with a null action (no side effect).
# The rest of script is only interpreted by awk.
#
exec awk -f "$0" -v "script=$0" "--" "$@" {}
BEGIN {
ARGC-- # skip the command line null action
for (i = 1; i < ARGC; i++) print ARGV[i]
exit
}

It has the following advantages:
- The location of awk has not to be hardwired in the script.
- no limitation about the pathname size, nor the number of args
(limitided respectively to 30, 1 in previous usage).
- the name of command is correctly passed as a variable
- works even if awk is a shell script (i.e. to automatically include other
files...).
- of course, allow to pass arguments starting with "-".

Cheers.

--Marc
Sponsored Links







Also available: Server administration forum archive | Web Design forum archive | Software forum archive | Hardware reviews archive

Copyright 2008 codecomments.com