bashshell

Get the name of the caller script in bash script


Let's assume I have 3 shell scripts:

script_1.sh

#!/bin/bash
./script_3.sh

script_2.sh

#!/bin/bash
./script_3.sh

the problem is that in script_3.sh I want to know the name of the caller script.

so that I can respond differently to each caller I support

please don't assume I'm asking about $0 cause $0 will echo script_3 every time no matter who is the caller

here is an example input with expected output

Is that possible? and if possible, how can it be done?

this is going to be added to a rm modified script... so when I call rm it do something and when git or any other CLI tool use rm it is not affected by the modification


Solution

  • Based on @user3100381's answer, here's a much simpler command to get the same thing which I believe should be fairly portable:

    PARENT_COMMAND=$(ps -o comm= $PPID)
    

    Replace comm= with args= to get the full command line (command + arguments). The = alone is used to suppress the headers.

    See: http://pubs.opengroup.org/onlinepubs/009604499/utilities/ps.html