1

我正在创建一个 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 永远不会加载。

请让我知道我能做些什么以防万一。

4

1 回答 1

0

如果您只是想异步*.app启动 Mac 应用程序 ( ) ,

  • open -a捆绑目录路径一起使用(以 结尾.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不带参数更健壮,后者的输出可以包括其他用户。

(顺便说一句, who | head -1 | head -1 | awk '{print $1;}'可以简化为更高效who | awk '{print $1; exit})。

于 2017-03-23T10:45:59.810 回答