How do I mimic in Awk Bash's 'cat "$0"'?

112 Views Asked by At

When I execute this script , ./cat-itself.sh it prints itself to stdout, without me having to give it any positional arguments explicitly from the terminal:

#!/usr/bin/bash

cat "$0"

How do I acomplish the same in Awk, Gawk specifically? My attempt is this

#!/usr/bin/awk -f

{
    print
}

but there are two issues with this: 1. It prints to stdout anything you give it as a positional parameter, e.g. ./cat-itself.awk cat-itself.awk 2. It requires a positional parameter to print anything to stdout. I want a script that would work when run like so ./cat-itself.awk

3

There are 3 best solutions below

0
Paolo On

With gawk (although not gawk specific) you could get the filename with this solution suggested by Ed Morton, and then you could use getline to print the contents of the file:

#!/usr/bin/gawk -f
BEGIN {
filename=ENVIRON["_"];
while ((getline line < filename) > 0)
  print line
close(filename)
}
$ ./awkcat.sh
#!/usr/bin/gawk -f
BEGIN {
filename=ENVIRON["_"];
while ((getline line < filename) > 0)
  print line
close(filename)
}

Alternatively, you could also run a system command to call cat:

#!/usr/bin/gawk -f
BEGIN {
filename=ENVIRON["_"];
system("cat" " " filename)
}
$ ./awkcat.sh
#!/usr/bin/gawk -f
BEGIN {
filename=ENVIRON["_"];
system("cat" " " filename)
}
0
Ed Morton On

Don't use a shebang to call awk

$ cat ./cat-itself
#!/usr/bin/env bash

awk '{ print }' "$0"

$ ./cat-itself
#!/usr/bin/env bash

awk '{ print }' "$0"

Also, and importantly: Unix commands don't have suffixes so if you have a command you want to call as ./cat-itself.awk then it should not be named cat-itself.awk, it should be named cat-itself instead so you can change it's implementation from awk to perl or shell or ruby or whatever you like without changing any other scripts you've written that call it.

The time to put a suffix on a file is when it's a library to be used by a specific tool or a file to be read by a tool (including a script for some tool to interpret). So if you have an awk script that you want to always interpret using awk -f cat-itself.awk then THAT is when you'd attach a suffix to it, not when it's a standalone command to be called as ./cat-itself.

0
glenn jackman On

With GNU awk and GNU coreutils env:

$ cat ./awk-itself
#!/usr/bin/env -S gawk -f
BEGIN {
    ARGV[ARGC++] = PROCINFO["argv"][2]
}
1

and

$ ./awk-itself
#!/usr/bin/env -S gawk -f
BEGIN {
    ARGV[ARGC++] = PROCINFO["argv"][2]
}
1

Docs: