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.
Subscribe to Newsletter
Software Updatesmore updates
- Fantastical 2.1 for iOS adds new snooze, search and notification features
- ExpanDrive 4, more services and faster sync
- Apple adds iTunes Extras to Apple TV
- Spotify updates with new iPhone controls in time for summer BBQs
- iTunes U update will bring course creation and student discussion to iPad app
- Dropbox for iOS update adds new setup and file management options