【问题标题】:Launchd Shell Script Execution FailsLaunchd Shell 脚本执行失败
【发布时间】:2015-01-07 23:28:42
【问题描述】:

我正在尝试使用 Launchd 运行以下 shell 脚本:

#!/bin/sh

## wait for sunset, touch file

NIGHTTIME='/Users/mnewman/Documents/webcam/nighttime.txt'

sunwait civ down  14.98N 102.09E
touch "$NIGHTTIME"

“sunwait”是一个在后台运行并等待日落/日出然后退出的可执行文件。在这种情况下,我将其设置为等到我所在地理位置的平民黄昏日落。

如果我从命令行运行这个脚本,它工作正常。如果我使用 Launchd 运行它,则 touch 命令会在 sunwait 完成之前运行。在执行下一行之前,我需要等待 sunwait 完成。我该怎么做?

【问题讨论】:

  • 你看到sunwait还在进程表中吗?也就是说,你怎么知道touchsunwait返回之前运行,而不是在这种情况下sunwait失败并提前退出?
  • 我强烈建议将exec >/tmp/wait-for-night.log 2>&1; set -x 放在脚本的开头,并在重现此行为后查看/tmp/wait-for-night.log 的内容。
  • (顺便说一句——我鼓励您对脚本范围内的变量使用小写名称,例如NIGHTTIME;按照惯例,全大写名称保留给环境变量和内置函数,这样对 shell 变量使用小写名称可以防止无意的冲突)。

标签: shell launchd


【解决方案1】:

这里最有可能的情况是您将sunwait 安装在不在launchd 的PATH 中的位置。解决方案是简单地指定 PATH 在您的脚本中使用 - 作为安全措施,如果 sunwait 失败,则告诉您的脚本不要创建文件。

#!/bin/sh
PATH=/bin:/usr/bin:/usr/local/bin:/opt/local/bin
nighttime=/Users/mnewman/Documents/webcam/nighttime.txt

sunwait civ down  14.98N 102.09E || exit
touch "$nighttime"

如果sunwait 运行失败,将shebang 行更改为#!/bin/sh -e 也会导致脚本提前退出,尽管使用set -e 有很多注意事项(记录在BashFAQ #105)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-20
    • 2015-11-14
    • 1970-01-01
    • 1970-01-01
    • 2016-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多