Sometimes you want a shell script to have different behavior depending upon how it was invoked. One trick I've used in that situation is to walk the process tree backwards and see what invoked the script. You can do that using ps or by looking in /proc. PPID is probably in your environment already, so it can be as simple as
ps -p $PPID -o cmd or ps -p $PPID -o comm
Of course that may not be far enough up the tree to find out whatever it is you need to know. For example, see How do I find out who or what halted my system (Old Sco Unix)?.
In some cases, it's not so much what invoked the script as what it is running under: is it reading from a pipe, for example. The "tty" command can tell you that:
$ cat t.sh tty || exit 1 echo "OK" $ ./t.sh /dev/pts/0 OK $ date | ./t.sh not a tty
Got something to add? Send me email.
More Articles by Tony Lawrence © 2009-11-07 Tony Lawrence
Being able to break security doesn’t make you a hacker anymore than being able to hotwire cars makes you an automotive engineer. (Eric Raymond)