4

I have a simple executable awk script which I'm trying to make to say its own name:

$ cat script.awk
#!/usr/bin/awk -f
BEGIN {
    print "Hi, I'm " ARGV[0]
}

when executed:

$ chmod u+x script.awk
$ ./script.awk
Hi, I'm awk

Expected (well, desired anyway) output would be Hi, I'm script.awk. Is there a way to achieve that except turning it to a shell script, like:

$ cat script.sh
#!/bin/bash
read -d '' script <<EOF
BEGIN {
    print "Hi, I'm " var
}
EOF
awk -v var=$0 "$script"

aaand, action:

$ ./script.sh
Hi, I'm ./script.sh
James Brown
  • 36,089
  • 7
  • 43
  • 59

1 Answers1

2

In bash or zsh, you can use the shell environment variable $_ via ENVIRON["_"]:

$ cat script.awk
#!/usr/bin/awk -f
BEGIN {
  print "Hi, I'm " ENVIRON["_"]
}
$ chmod u+x script.awk
$ ./script.awk
Hi, I'm /tmp/./script.awk

The ENVIRON array is an awk special variable defined in the POSIX standard, so it should be readily available in any version of awk, but different shells implement $_ differently, so this is only reliable if you are invoking it from bash or zsh.

This will not work in dash (commonly installed as /bin/sh) since dash assigns the previous command to $_ (if this is the first command, it will instead assign itself).

Korn Shell (ksh93, at least) prefixes the shell's PID (surrounded by asterisks) to the value, like *12345*./script.awk, so it needs a slight modification.

This version will work in bash, zsh, and ksh:

#!/usr/bin/awk -f
BEGIN {
  self = ENVIRON["_"]
  sub(/^\*[0-9]+\*/, "", self)
  print "Hi, I'm " self
}
Adam Katz
  • 14,455
  • 5
  • 68
  • 83
  • Also: I can't get `ENVIRON["$"]` to get the value of `$$` (with mawk 1.3.4), so you can't easily get the current PID. The PID might otherwise have allowed a `getline` command involving `ps -f`. You can still do it with `pstree` or `ps --forest`, but that'd be _really_ ugly and those aren't very portable. – Adam Katz Sep 02 '21 at 21:17