If you want to set environment variables in OS X in such a way as to be recognised in applications run from Finder, it is not enough to set the env var in .profile. You must also ensure that the variables are set in the file ~/.MacOSX/environment.plist. Setting values in that file is most conveniently done using the executable PlistBuddy.
On my system, the command
$ which PlistBuddy
yields
/usr/sbin/PlistBuddy
Here’s some code you can add to .profile to set both environment.plist and the bash environment variables.
Create the following functions in .profile.
set_env_var () {
eval export $1=””$2″”
set_plist_var “$1” “$2”
}
set_plist_var () {
# Check current value of plist var
local current=`PlistBuddy -c ‘Print :'”$1″ ~/.MacOSX/environment.plist`
if [ `expr “$current” : ‘Print.* Not Exist’` = “0” ]
then # Variable exists
# Is the current value changing?
if [ X”$current” != X”$2″ ]; then
PlistBuddy -c ‘Set :'”$1″‘ “‘”$2″‘”‘ ~/.MacOSX/environment.plist
fi
else # Variable does not exist
echo $current
PlistBuddy -c ‘Add :'”$1″‘ string “‘”$2″‘”‘ ~/.MacOSX/environment.plist
fi
}
You may then use the function set_env_var to set both bash and environment.plist entries. For example,
set_env_var M2_HOME “/usr/share/maven”
set_env_var M2 “$M2_HOME/bin”
set_env_var HTML_TIDY “$HOME/.tidy”
Note that the environment variables will immediately be available to any shell scripts or Terminal invocations, but any new variables which have been set in <em>~/.MacOSX/environment.plist</em> may not generally be available until you next login. I’m not sure at which points in a session, apart from login, <em>environment.plist</em> is read.
Originally published on 17 Dec 2011, and updated on 1 Mar 2012 at http://pbw.livejournal.com/8256.html.