Terminally Geeky: How to tell if a script is being called from launchd
Warning: command line geekiness ahead.
When writing shell scripts, I often send interactive output to the user via
echo to give feedback or information. But if the shell script is called on a schedule via OS X's behind-the-scenes process launcher
launchd, rather than from a Terminal session, chances are that I won't ever see that message.
Fortunately, it's relatively easy to figure out if a shell script has been called from
launchd or not, simply by checking the
$PPID variable. (Note: this works in
zsh and may work in
bash as well. If it doesn't work in your shell, this is a good time to upgrade to
But how can I make sure my messages are seen if a shell script has been called via
launchd? For that I use the Swiss Army Knife of notification tools, Growl. Specifically, I use the growlnotify optional package, which allows me to send Growl notifications from shell scripts.
For example, imagine that I wrote a script where I wanted to tell the user that a certain process had succeeded or failed. Normally I might just use
But now, instead of 'echo' I use a function called
msg (short for 'message'). If the script was called from
msg will use
growlnotify, but if the script was called from the command line, it will just use
echo. Here's how that works:
This method is not foolproof. For example, if you call a shell script from
launchd and that shell script calls another shell script, it might not realize that it was originally executed from launchd. In practice, I have not run into that problem, but it did seem worth mentioning.
A quick check to see if a shell script was called from launchd
Deals of the Daymore deals
Software Updatesmore updates
- Agile Partners releases Lick of the Day 2.0
- Microsoft Office for Mac 2011 Update 14.3.4
- Pixelmator 2.2 available with over 100 new features and improvements
- DabKick for iPhone lets you share photos, watch videos and now listen to music in real-time
- Google Now added to search app on iPhone, iPad
- GateGuru for iPhone has been updated and greatly improved