How would I determine what script, program, or shell executed my Perl script?
Example: I might want to have human readable output if executed from shell (customized for each type of shell), a different type of output if called as a script from another perl script, and a machine readable format if executed from a program such as a continuous integration server.
Motivation: I have a tool that changes its output based on which shell executes it. I'd normally implement this behavior as an option to the script, but this tool's design doesn't allow for options. Other shells have environment variables that indicate what shell is running. I'm working on a patch to support Powershell, which has no such special variable.
Edit: Many of these answers happen to be linux specific. Unfortuantely, Powershell is for Windows. getppid
, the $ENV{SHELL}
variable, and shelling out to ps
won't help in this case. This script needs to run cross-platform.
You use getppid(). Take this snippet in child.pl
:
my $ppid = getppid();
system("ps --no-headers $ppid");
If you run it from the command line, system
will show bash
or similar (among other things). Execute it with system("perl child.pl");
in another script, e.g. parent.pl
, and you will see that perl parent.pl
executed it.
To capture just the name of the process with arguments (thanks to ikegami for the correct ps
syntax):
my $ppid = getppid();
my $ps = `ps --no-headers -o cmd $ppid`;
chomp $ps;
EDIT: An alternative to this approach, might be to create soft links to your script, make the different contexts use different links to access your script and inspect $0
to build logic around that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With