1

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.

asked Jan 1, 2017 at 20:30
2
  • What method do you use to start atom? Which version for the app and which build / version for macOS. Commented Aug 31, 2018 at 21:21
  • I start it from the application bundle, and use High Sierra. Commented Sep 3, 2018 at 23:12

1 Answer 1

2

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 &lt; $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 &lt; $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
 &lt; # Since a plist is an xml document, angle brackets must be escaped. 
 &lt; $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.

techraf
4,1068 gold badges27 silver badges45 bronze badges
answered Jan 1, 2017 at 20:30
2
  • 1
    Doesn't seem to work in High Sierra. Commented Aug 31, 2018 at 20:43
  • Still works for me. Commented Sep 3, 2018 at 23:11

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.