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

akn*_*akn 1 macos bash launchd plist

我有一个简单的脚本,可以在文件发生更改时将其上传到保管箱。我想在系统启动时运行它并将其保留在后台以便让脚本监视文件。

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

列表

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

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

launchtl list输出

 ~> launchctl list | grep com.example                                                                                                                       (base) 
-   0   com.example.launchd.dropbox_uploader
Run Code Online (Sandbox Code Playgroud)

如何实现让它在后台运行的目标?我不确定我的 plist 或脚本是否有问题。

akn*_*akn 5

正如戈登在评论中提到的那样启用文件输出有助于找到原因。

问题是:

/Users/me/dropbox-uploader.sh: line 3: fswatch: command not found
Run Code Online (Sandbox Code Playgroud)

因此更改fswatch为绝对fswatchbin 路径/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'
Run Code Online (Sandbox Code Playgroud)

启用文件输出的 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>
Run Code Online (Sandbox Code Playgroud)