Quantcast
Viewing all articles
Browse latest Browse all 6

Answer by fedorqui for How to print own script name in mawk?

Using GNU awk

Checking the GNU awk user's guide - 7.5.2 Built-in Variables That Convey Information I stumbled upon:

PROCINFO #

The elements of this array provide access to information about the running awk program. The following elements (listed alphabetically) are guaranteed to be available:

PROCINFO["pid"]

The process ID of the current process.

This means that you can know the PID of the program during runtime. Then, it is a matter of using system() to look for the process with this given PID:

#!/usr/bin/gawk -f
BEGIN{ pid=PROCINFO["pid"]
       system("ps -ef | awk '$2==" pid " {print $NF}'")
}

I use ps -ef, which displays the PID on the 2nd column. Assuming the executiong is done through awk -f <script> and no other parameters, we can assume the last field of the line contains the information we want.

In case we had some parameters, we would have to parse the line differently -or, better, use some of the options of ps to print just the columns we are interested in.

Test

$ awk -f a.awk 
a.awk
$ cp a.awk hello.awk
$ awk -f hello.awk 
hello.awk

Note also that another chapter of the GNU awk user's guide tells us that ARGV is not the way to go:

1.1.4 Executable awk Programs

Finally, the value of ARGV[0] (see 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’). (d.c.) Don’t rely on the value of ARGV[0] to provide your script name.


Viewing all articles
Browse latest Browse all 6

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>