Advertisement

Terminal Tips: bash cron script to keep an app running

Do you have some apps that you want to keep running all the time? If so, and if you're not afraid of the Terminal or the command line, I have a script for you.

When I come home at the end of the day, Dropbox has stopped running on my iMac. I'm running the latest version, and it works fine on my MacBook Pro, but for some reason, this just keeps happening. The script has nothing to do with Dropbox itself; you could substitute any app that you always want running, such as LaunchBar, OmniFocus, 1Password, or any other app that you like.

It's fairly simple:

#!/bin/sh

PATH=/bin:/usr/bin

# Change 'Dropbox' to whatever app you want. Be sure to capitalize
# it correctly and include any spaces. You do not need to add .app
APPNAME="Dropbox"

# if the app name _IS_ found in process list, exit
ps xc|fgrep "${APPNAME}" >/dev/null && exit 0

# if the app isn't found, open it
open -a "${APPNAME}"

exit 0

That's it. Now, you save the file (I call mine "keep-my-app-running.sh"); I saved it to ~/bin/, but you can put it anywhere you want.

Be sure to type 'chmod +x /Users/luomat/bin/keep-my-app-running.sh' (or wherever it is saved) to tell OS X it is an eXecutable file. (Thanks to Justin for reminding me about this in the comments below.)

Now, we need to tell cron to run it. Some folks will tell you to use launchd, but cron works well and it's easy, so we'll use that. To do that, create a ~/.crontab file using your favorite text editor. If it already exists, just keep whatever's there, and add this line at the bottom:

*/5 * * * * /Users/luomat/bin/keep-my-app-running.sh

Change "luomat" to whatever your login name is, and change "keep-my-app-running.sh" to whatever you named the script. This tells cron to check if your app is running every 5 minutes or so. You can change the 5 to something else if you want to change the frequency. The last step is to tell cron to load the new file you've created:

crontab ~/.crontab

If you want to verify that it worked, run 'crontab -l' to see if your crontab is listed properly. It may also be a good idea to run 'crontab -l' before you begin in order to make sure that there isn't anything already in there. Most likely there isn't, or if there is, you already know about it.

Update: As noted in the comments, cron works fine, but launchd can be configured to relaunch Dropbox as soon as it exits. I've enclosed a picture of a Lingon screenshot below, or you can see the plist that it creates. Lingon is no longer developed, but it works fine for me under Snow Leopard.

I tried to use launchd to run a script at 0, 15, 30, and 45 minutes past the hour, which I can do in cron using this:

*/15 * * * * /path/to/script.sh

but launchd didn't keep that schedule (for example, it posted at 11:48 and 12:03). So I decided to keep using cron for that, although launchd is a much better option for the 'keep alive' purpose.

%Gallery-105694%