我正在创建 macOS 安装程序包。
为此,我使用安装后脚本文件来启动应用程序,然后加载 LaunchDaemon plist。
这是安装后脚本:
#!/bin/bash
cd /usr/local/TestApp
USER_NAME=$(who | head -1 | head -1 | awk '{print $1;}')
sudo -u $USER_NAME /usr/local/TestApp/Test.app/Contents/MacOS/Test -l
sudo launchctl load /Library/LaunchDaemons/com.testapp.plist
结果是它使用
sudo -u $USER_NAME /usr/local/TestApp/Test.app/Contents/MacOS/Test -l
命令启动应用程序,然后阻止,因为应用程序一直在运行。
因此,脚本会卡住,并且 LaunchDaemon 永远不会加载。
请告诉我以防万一我可以做什么。
如果您只想启动 Mac 应用程序 (
*.app
) 异步,
open -a
与 bundle 目录路径一起使用(以 .app
结尾)--args
之后传递任何直通命令行参数(请参阅 man open
):sudo -u $USER_NAME open -a /usr/local/TestApp/Test.app --args -l
请参阅底部的注释,重新可靠地确定调用用户的用户名
$USER_NAME
。
如果由于某种原因,您确实需要直接定位
*.app
捆绑包中嵌入的可执行文件,则必须使用 Bash 的 &
控制运算符在 后台中运行命令:
#!/bin/bash
# Get the underlying username (see comments below).
userName="${HOME##*/}"
# Launch the app in the background, using control operator `&`
# which prevents the command from blocking.
# (Given that the installer runs the script as the root user,
# `sudo` is only needed here for impersonation.)
sudo -u "$userName" /usr/local/TestApp/Test.app/Contents/MacOS/Test -l &
# Load the daemon.
# (Given that the installer runs the script as the root user,
# `sudo` is not needed here.)
launchctl load /Library/LaunchDaemons/com.testapp.plist
请注意,我更改了确定基础用户名的方式:
${HOME##*/}
从底层用户的主目录路径
$HOME
中提取最后一个路径组件,该路径反映了调用安装程序的用户。
who
更强大,后者的输出可以包括
other用户。
who | head -1 | head -1 | awk '{print $1;}'
可以简化为更高效的
who | awk '{print $1; exit}
)。