launchd - 如何在后台保留脚本 运行

launchd - how to keep script running in the background

我有一个简单的脚本可以在文件发生变化时将其上传到保管箱。我想 运行 在系统启动时将其保存在后台以让脚本监视文件。

我已经创建了一个 plist,但是它 运行 是脚本并以代码 0 退出。

plist

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.example.launchd.dropbox_uploader</string>
    <key>ProgramArguments</key>
    <array>
        <string>sh</string>
        <string>-c</string>
        <string>~/dropbox-uploader.sh; wait</string>
    </array>
    <key>RunAtLoad</key>
    <true/>
</dict>
</plist>

(命令中有或没有 wait 都不起作用)

脚本(它工作正常并且在命令行中 运行 时不会退出)

#!/bin/sh

fswatch -o ~/file.txt | xargs -n1 -I{} curl -X POST https://content.dropboxapi.com/2/files/upload \
    --header 'Authorization: Bearer XXXXX' \
    --header 'Content-Type: application/octet-stream' \
    --header 'Dropbox-API-Arg: {"path":"/backup/file.txt","strict_conflict":false,"mode":{".tag":"overwrite"}}' \
    --data-binary @'~/file.txt'

launchtl list输出

 ~> launchctl list | grep com.example                                                                                                                       (base) 
-   0   com.example.launchd.dropbox_uploader

如何实现将其 运行 置于后台的目标?我不确定我的 plist 或脚本是否有问题。

使用 crontab -e 编辑 crontab 文件并将以下内容添加到该文件:

@reboot /path/to/job

这将在您的系统每次重新启动时 运行 您的工作,并将其 运行 保留在后台。

启用文件输出为有助于找到原因。

问题是:

/Users/me/dropbox-uploader.sh: line 3: fswatch: command not found

因此将 fswatch 更改为绝对 fswatch bin 路径 /usr/local/bin/fswatch 解决了问题。我还将 ~/ 替换为 plist 中的绝对路径,并确保该脚本是可执行的。

最终脚本:

#!/bin/sh

/usr/local/bin/fswatch -o ~/file.txt | xargs -n1 -I{} curl -X POST https://content.dropboxapi.com/2/files/upload \
    --header 'Authorization: Bearer XXXX' \
    --header 'Content-Type: application/octet-stream' \
    --header 'Dropbox-API-Arg: {"path":"/backup/file.txt","strict_conflict":false,"mode":{".tag":"overwrite"}}' \
    --data-binary @'~/file.txt'

启用文件输出的 plist

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.example.launchd.dropbox_uploader</string>
    <key>ProgramArguments</key>
    <array>
        <string>/Users/me/dropbox-uploader.sh</string>
    </array>
    <key>RunAtLoad</key>
    <true/>
    <key>StandardOutPath</key>
    <string>/Users/me//dropbox.out</string>
    <key>StandardErrorPath</key>
    <string>/Users/me/dropbox.err</string>
</dict>
</plist>