问题描述
我有一个简单的脚本,可以在文件发生变化时将文件上传到 DropBox。我想在系统启动时运行它并将其保留在后台让脚本监视文件。
我创建了一个 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>
(在命令中使用或不使用 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 或脚本是否有问题。
解决方法
启用文件输出为 Gordon mentioned in his comment 有助于找到原因。
问题是:
/Users/me/dropbox-uploader.sh: line 3: fswatch: command not found
因此将 fswatch
更改为绝对 fswatch
bin path /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>
,
使用 crontab -e
编辑 crontab 文件并将以下内容添加到该文件中:
@reboot /path/to/job
这将在您每次系统重新启动时运行您的作业并使其在后台运行。