How to print own script name in mawk?

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.


I don't think this is possible as per gawk documentation:

Finally, the value of ARGV[0] (see section 7.5 Built-in Variables) varies depending upon your operating system. Some systems put awk there, some put the full pathname of awk (such as /bin/awk), and some put the name of your script ('advice'). Don't rely on the value of ARGV[0] to provide your script name.

On linux you can try using a kind of a dirty hack and as pointed in comments by Stéphane Chazelas it is possible if implementation of awk supports NUL bytes:

#!/usr/bin/awk -f

BEGIN { getline t < "/proc/self/cmdline"; split(t, a, "\0"); print a[3]; }

I don't know any direct way of getting the command name from within awk. You can however find it through a sub-shell.

gawk

With GNU awk and the ps command you can use the process ID from PROCINFO["PID"] to retrieve the command name as a workaround. For example:

cmdname.awk

#!/usr/bin/gawk -f

BEGIN {
  ("ps -p " PROCINFO["pid"] " -o comm=") | getline CMDNAME
  print CMDNAME
}

mawk and nawk

You can use the same approach, but derive awk's PID from the $PPID special shell variable (PID of the parent):

cmdname.awk

#!/usr/bin/mawk -f

BEGIN { 
  ("ps -p $PPID -o comm=") | getline CMDNAME
  print CMDNAME
}

Testing

Run the script like this:

./cmdname.awk

Output in both cases:

cmdname.awk