Script calling hierarchy

If a.sh calls b.sh, how can we know inside b.sh that it was called by a.sh?

The variable $PPID contains the PID of the parent process. You need to parse the output of ps (or know how to fish it out of the /proc file system if your OS has that) to find the name of the command of that PID.

As long as this isn't for security reasons, finding out the name isn't so tough. Check your ps command, which might contain the option to spit out the command name of a given pid. For instance, on Linux, I can do this:

ps --no-header -o cmd $PPID

Thanks both of you who've replied. I've successfully verified its utility. See below:

[root@IMITS174 perl_scripts]# cat a.sh
#!/bin/sh

sh b.sh
[root@IMITS174 perl_scripts]#
[root@IMITS174 perl_scripts]#
[root@IMITS174 perl_scripts]# cat b.sh
#!/bin/sh

echo "I am b"
parent_name=`ps --no-header -o ucmd $PPID`
echo "Parent PID is $PPID"
echo "Parent is $parent_name"
[root@IMITS174 perl_scripts]#
[root@IMITS174 perl_scripts]# ./a.sh
I am b
Parent PID is 18251
Parent is a.sh
[root@IMITS174 perl_scripts]#
[root@IMITS174 perl_scripts]#
[root@IMITS174 perl_scripts]# ./b.sh
I am b
Parent PID is 2014
Parent is bash

Note however: I've changed "cmd" to "ucmd" to make sure I don't get the annoying "/bin/sh" prefix to the calling program a.sh.

Thanks once again! Hope the above snippet helps anyone who wants to use it.

By the way, what would you do in case of Windows? Assume instead of .sh, you are dealing with .pl....?