Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set environment variable for the process before startup

I have the following situation:

I have Mac OS bundle with application which uses some 3rd party dynamic libraries and those libraries depend on some environment variable, let's name it ENV_VAR. I want to set ENV_VAR to some value for my application only because if I set it for the whole system it may breaks some other apps. And it should work transparently to the user i.e. he just run my app from the Application folder by double clicking it. How can I achieve it?

NOTE: dynamic libraries are loaded before main functions starts hence setting this variable in the main doesn't help.

like image 487
ixSci Avatar asked Sep 14 '25 10:09

ixSci


1 Answers

You can add a key "LSEnvironment" to your app bundle's Info.plist. The value can be a dictionary with strings for keys and values and those key-value pairs will be added to the environment when your app is launched by Launch Services (e.g. from the Finder or Dock but not from the Terminal).

<key>LSEnvironment</key>
<dict>
    <key>ENV_VAR</key>
    <string>value</string>
</dict>

However, in my testing (on Snow Leopard), it was a bit flaky to test, at least when editing the Info.plist of an existing app. Basically, Launch Services caches this part of the app's Info.plist when it first encounters the app and won't necessarily recognize changes on disk. You can sometimes prompt it to reread the Info.plist by, for example, duplicating the app bundle or temporarily moving it to a different folder. Of course, the overkill solution would be to use lsregister to flush and rebuild the cache:

/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister -kill -seed

This caching issue won't affect your end users, just you as you tweak the Info.plist. Also, it shouldn't affect you if you make the change in your source Info.plist and then build the app using Xcode.

like image 188
Ken Thomases Avatar answered Sep 16 '25 09:09

Ken Thomases