How to print own script name in mawk

awkmawkscripting

In bash $0 contains the name of the script, but in awk if I make a script named myscript.awk with the following content:

#!/usr/bin/awk -f
BEGIN{ print ARGV[0] }

and run it, it will only print "awk". Besides, ARGV[i] with i>0 is used only for script arguments in command line.
So, how to make it print the name of the script, in this case "myscript.awk"?

Best Answer

With GNU awk 4.1.3 in bash on cygwin:

$ cat tst.sh
#!/bin/awk -f
BEGIN { print "Executing:", ENVIRON["_"] }

$ ./tst.sh
Executing: ./tst.sh

I don't know how portable that is. As always, though, I wouldn't execute an awk script using a shebang in a shell script as it just robs you of possible functionality. Keep it simple and just do this instead:

$ cat tst2.sh
awk -v cmd="$0" '
BEGIN { print "Executing:", cmd }
' "$@"

$ ./tst2.sh
Executing: ./tst2.sh

That last will work with any modern awk in any shell on any platform.

Related Question