MacOS – Setting environment variables for scripts run by launchd

bashlaunchdmacosscriptterminal

I have a script that worked in the past, but seems to be having issues now (I believe it's due to Yosemite). What I had done was created an environment variable that was set to "false" and then my script would set it to "true" so that if the script took too long and started again before it finished it would not attempt to run again concurrently. However, it doesn't work anymore.

I set the variable initially with /etc/launchd.conf

setenv autoBackupImagesInProgress false

And the part of my script that doesn't work anymore is

#Ensure that this script isn't already running
if [ -z "$autoBackupImagesInProgress" ] ; then
   #Concurrency variable was not setup so this will not work;
   #edit .bashrc or .profile to include export autoBackupImagesInProgress=false
   #should be /etc/launchd.conf
   print "WARNING: Concurrency protection unavailable"
elif [ $autoBackupImagesInProgress = true ] ; then
   #Another process has already started this, but has not yet finished
   print "WARNING: Already in progress; aborting."
   exit 0;
fi

This works if I initiate the script from the terminal or Spotlight, but not when this is started with launchd. When run from launchd this will always print the first warning and never hits the elif.

Best Answer

Open your Script Editor(Launch Pad -> Other -> Script Editor) Type scripts like this:

do shell script "launchctl setenv autoBackupImagesInProgress false"

Use multiple lines if you want to set multiple variables.

Save this script as Application, open SystemPreferences → Users & Groups → your user → Login Items and add your saved script.

To apply changes, logout your account and log in again.