在启动脚本中使用环境变量

mat*_*pie 29 mac-osx osx-leopard environment-variables launchd

我很好奇是否可以ProgramArguments在 Mac OS X Leopard 上的 luanchd 脚本部分指定环境变量。

<?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>
Run Code Online (Sandbox Code Playgroud)

Joe*_*ock 24

不在 ProgramArguments 键中。您需要EnvironmentVariables在 plist 的 dict 中添加一个键,如下所示:

<?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>
Run Code Online (Sandbox Code Playgroud)

请参阅:创建启动守护程序和代理

  • 当然,您可以对环境进行硬编码。plist 中的变量,但您不能使用现有的变量,如 $HOME。除非它只是一个 shell 脚本的参数,在这种情况下,shell(不是 launchd)将扩展它。但是在这个例子中,如果你将 `-c` 选项添加到 /bin/sh 中,它可能真的有效吗? (4认同)

小智 6

处理这个问题的最佳方法是将命令包装在 shell 中。例如:

\n\n
<?xml version="1.0" encoding="UTF-8"?>\n<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n<plist version="1.0">\n<dict>\n    <key>KeepAlive</key>\n    <false/>\n    <key>Label</key>\n    <string>sh.daniel.envvar</string>\n    <key>ProgramArguments</key>\n    <array>\n        <string>/bin/zsh</string>\n        <string>-c</string>\n        <string>echo \'You did the thing!\' > $HOME/did-the-thing.log</string>\n    </array>\n    <key>RunAtLoad</key>\n    <true/>\n</dict>\n</plist>\n
Run Code Online (Sandbox Code Playgroud)\n\n
\xe2\x9d\xaf cat ~/did-the-thing.log\nYou did the thing!\n
Run Code Online (Sandbox Code Playgroud)\n\n

该标志-c告诉 ZSH(以及 Bash 和 sh)运行 next.txt 中指定的命令。如果添加标志-l,它\xe2\x80\x99 将在执行之前加载你的点文件,就像普通的登录 shell 一样。

\n


Dav*_*and 1

我不确定 - 我以前没有尝试过......但我可以告诉你,如果你关心的唯一变量是 home - 你可以使用 ~.

So: <string>~/bin/attach-devroot.sh</string>
Run Code Online (Sandbox Code Playgroud)

  • 不再支持“EnableGlobbing” (2认同)