MacOS – Dynamically setting HOME environment variable in a launchd script

environment-variableshomebrewlaunchdmacosplist

Continue from this topic, I ended up with:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
  <dict>
    <key>Label</key>
    <string>com.saltstack.minion</string>
    <key>EnvironmentVariables</key>
    <dict>
      <key>HOME</key>
      <string>/Users/quanta</string>
    </dict>
    <key>ProgramArguments</key>
    <array>
      <string>/usr/local/bin/salt-minion</string>
    </array>
    <key>RunAtLoad</key>
    <true/>
  </dict>
</plist>

but I am wonder that: is there any way to set HOME variable dynamically? (instead of fixed code – /Users/quanta)

I have tried to add an EnableGlobbing key to the plist:

<key>EnableGlobbing</key>
<true/>

then changed the value of HOME variable to the tilde:

<key>EnvironmentVariables</key>
<dict>
  <key>HOME</key>
  <string>~</string>
</dict>

and restart the salt-minion. Here is what I get:

MacBook-Pro.local:
    - /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/pathname.rb:853:in `expand_path': non-absolute home (ArgumentError)
    -   from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/pathname.rb:853:in `expand_path'
    -   from /usr/local/Library/Homebrew/global.rb:25:in `cache'
    -   from /usr/local/Library/Homebrew/global.rb:44
    -   from /usr/local/Library/brew.rb:17:in `require'
    -   from /usr/local/Library/brew.rb:17

It seems that expansion is only enabled for strings in the Program or ProgramArguments keys.

Best Answer

You are right: launchd performs tilde-expansion only for ProgramArguments. But you are free to let a shell do the job:

<key>ProgramArguments</key>
<array>
    <string>/bin/sh</string>
    <string>-c</string>
    <string>export HOME=~; /usr/local/bin/salt-minion</string>
</array>

Note that the ~ in this example is not interpreted by launchd (using EnableGlobbing) but by the shell itself.