How do you set an environment variable on startup so that it can be used in applications?
For example, ATOM_HOME is used by Atom.
-
What method do you use to start atom? Which version for the app and which build / version for macOS.bmike– bmike ♦2018年08月31日 21:21:20 +00:00Commented Aug 31, 2018 at 21:21
-
I start it from the application bundle, and use High Sierra.0az– 0az2018年09月03日 23:12:03 +00:00Commented Sep 3, 2018 at 23:12
1 Answer 1
Solution
The solution uses two files: environment.plist and environment.conf.
environment.plist should be placed in ~/Library/LaunchAgents for a per user solution (recommended), or in /Library/LaunchAgents for a global solution (not recommended – potential security loophole).
environment.conf can be placed almost anywhere. $PATH_TO_ENVIRONMENT_CONF can be relative, but only to the 'default' environment variables, or any that are defined in a EnvironmentVariables key. 1
environment.plist:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>local.launchd.environment</string>
<key>ProgramArguments</key>
<array>
<string>sh</string>
<string>-c</string>
<string>xargs -L 1 launchctl < $PATH_TO_ENVIRONMENT_CONF</string>
</array>
<key>RunAtLoad</key>
<true/>
</dict>
</plist>
environment.conf:
setenv ATOM_HOME $HOME/.config/atom
setenv SOME_VAR "Use quotes if spaces are necessary"
How it works
When a user logs in, the LaunchAgents in ~/Library/LaunchAgents are executed. In this case, sh -c xargs -L 1 launchctl < $PATH_TO_ENVIRONMENT_CONF is executed. launchctl manages daemons and agents. In this case, we are using it to set an environment variable accessible to all applications and the shell.
xargs -L 1 launchctl < $PATH_TO_ENVIRONMENT_CONF
xargs # xargs converts stdin to command line arguments
xargs -L 1 # Tells xargs to invoke launchctl for each line
launchctl # Run launchctl with the arguments
< # Since a plist is an xml document, angle brackets must be escaped.
< $PATH_TO_ENVIRONMENT_CONF
# This tells xargs to read input from the file at $PATH_TO_ENVIRONMENT_CONF
This solution can also be extended to other launchctl subcommands.
-
1Doesn't seem to work in High Sierra.user2752467– user27524672018年08月31日 20:43:04 +00:00Commented Aug 31, 2018 at 20:43
-
You must log in to answer this question.
Explore related questions
See similar questions with these tags.