【发布时间】:2021-06-11 17:40:52
【问题描述】:
我的目标是备份我每天保存在/Users/<me>/codes/notes 文件夹中的一些降价笔记。我有一个 crontab 作业设置,每分钟运行一次以进行故障排除,但最终我希望每天都运行一次。
crontab 作业
* * * * * cd ~/codes/notes && ./backup_notes.sh
backup_notes.sh
#!/bin/sh
# create a timestamp alias for the commit message
timestamp() {
date +"%Y-%m-%d @ %T"
}
# Go to my notes folder
cd /Users/<me>/codes/notes
# pull & push
if [[ `git status --porcelain` ]]; then
git pull origin main
git add .
git commit -m "Update: $(timestamp)"
git push origin main
fi
我相信脚本本身可以工作,因为我可以做到:
❯ ./backup_notes.sh
并将更改推送到 github 上的远程存储库。
我还相信 crontab 作业正在触发,因为如果我将 echo "hello world" > ./log.txt 添加到 backup_notes.sh 的顶部,我将在 ./log.txt 中获得预期的 hello world
如果有人对我如何解决问题有任何建议,我会很困惑。
我尝试过的事情:
- 将
git替换为/usr/local/bin/git - 删除条件
- 双重检查
chmod 744 ~/codes/notes/backup_notes.sh - 添加了
* * * * * cd ~/codes/notes && echo "hello world" > ./log.txt以验证crontab 是否正常工作,这会将hello world放入log.txt。
我还加了一些echos:
#!/bin/bash
# create a timestamp alias for the commit message
timestamp() {
date +"%Y-%m-%d @ %T"
}
# Go to my notes
cd /Users/jesse.spevack/codes/notes
echo "job started: $(timestamp)" > log.txt
# pull & push
if [[ `git status --porcelain` ]]; then
echo "Running Git commands: $(timestamp)" >> log.txt
git pull origin main
git add .
git commit -m "Update: $(timestamp)"
git push origin main
echo "Finished running Git commands: $(timestamp)" >> log.txt
fi
echo "job done: $(timestamp)" >> log.txt
这会将以下内容添加到我的log.txt:
job started: 2021-03-14 @ 09:12:00
Running Git commands: 2021-03-14 @ 09:12:00
Finished running Git commands: 2021-03-14 @ 09:12:01
job done: 2021-03-14 @ 09:12:01
但是,对 github 上的远程仓库没有影响。
【问题讨论】:
-
BTW 双括号符号
[[是一种 bashism,因此您应该将 shebang 更改为 bash(尽管我认为这不是根本原因,因为您提到它在没有条件的情况下也会失败)。 -
对于调试,请尝试在您的 repo 中保留未暂存的更改,然后在 cronjob 触发后检查 repo 状态以查看这些更改是否仍然未暂存、暂存、已提交等。
标签: bash git shell github cron