Sunday, January 23, 2011

Use an environment variable in a launchd script

I'm curious if it's possible to specify an envrionment variable in the ProgramArguments portion of a luanchd script on Mac OS X Leopard.

<?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>me.mpietz.MountDevRoot</string>
    <key>ProgramArguments</key>
    <array>
        <string>/bin/sh</string>

        <string>$HOME/bin/attach-devroot.sh</string>

        <!-- Instead of using...
        <string>/Users/mpietz/bin/attach-devroot.sh</string -->
    </array>
    <key>RunAtLoad</key>
    <true/>
</dict>
</plist>
  • I'm not sure - I haven't tried it before... but I can tell you that if the only variable you care about is home - you can use ~.

    So: <string>~/bin/attach-devroot.sh</string>
    
    sirlancelot : This doesn't work. I get `"/bin/sh: ~/bin/attach-devroot.sh: No such file or directory"`
  • I don't think launchd knows about the environment natively, at least not as ${VARIABLE} substitutions.

    There's nothing stopping you from launching a shell script (or a shell with -c) as your launchd action though, and that would have an environment and respect ${VARIABLES} -- Be aware of the difference between System and User daemons/agents in that case though...

    From voretaq7
  • Not in the ProgramArguments key. You need to add an EnvironmentVariables key into your plist's dict like so:

    <?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>EnvironmentVariables</key>
        <dict>
               <key>AN_ENVIRONMENT_VARIABLE_NAME</key>
               <string>the_value</string>
        </dict>
        <key>Label</key>
        <string>me.mpietz.MountDevRoot</string>
        <key>ProgramArguments</key>
        <array>
            <string>/bin/sh</string>
    
            <string>$HOME/bin/attach-devroot.sh</string>
    
            <!-- Instead of using...
            <string>/Users/mpietz/bin/attach-devroot.sh</string -->
        </array>
        <key>RunAtLoad</key>
        <true/>
    </dict>
    </plist>
    
    From jpb

No comments:

Post a Comment