APLawrence.com -  Resources for Unix and Linux Systems, Bloggers and the self-employed

2005/06/05 How does a shell script know how it was invoked?

© June 2005 Tony Lawrence

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


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
$ date | ./t.sh
not a tty

Got something to add? Send me email.

(OLDER)    <- More Stuff -> (NEWER)    (NEWEST)   

Printer Friendly Version

-> 2005/06/05 How does a shell script know how it was invoked?


Inexpensive and informative Apple related e-books:

Take Control of Upgrading to El Capitan

Take Control of Preview

Take Control of IOS 11

Take Control of Apple Mail, Third Edition

Take Control of Parallels Desktop 12

More Articles by © Tony Lawrence

Sun Jun 5 06:17:34 2005: 614   anonymous

You can also use this:

if [ -t 0 ] 
    echo "Reading from a terminal!" 
if [ -t 1 ] 
    echo "Writing to a terminal! 


PS: Why does "pre" tag not work very well here?

Sun Jun 5 09:52:24 2005: 615   TonyLawrence

PRE doesn't work well simply because I haven't taken the time to fix the code.


Printer Friendly Version

Have you tried Searching this site?

This is a Unix/Linux resource website. It contains technical articles about Unix, Linux and general computing related subjects, opinion, news, help files, how-to's, tutorials and more.

Contact us

Printer Friendly Version

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)

Linux posts

Troubleshooting posts

This post tagged:



Unix/Linux Consultants

Skills Tests

Unix/Linux Book Reviews

My Unix/Linux Troubleshooting Book

This site runs on Linode