我的目标是备份我保存在 /Users/<me>/codes/notes
中的一些 Markdown 笔记每日文件夹。我有一个 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
我会得到预期的 hello world
在 ./log.txt
我很困惑,如果有人对我如何进行故障排除有任何建议,我将不胜感激。
我尝试过的事情:
- 替换
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上的远程仓库没有影响。
最佳答案
在简化的环境下运行你的脚本,比如
env -i HOME=$HOME ./backup_notes.sh
您可能会发现该脚本应该设置 PATH
或一些在 cron 环境中找不到的其他变量。要检查(相当有限的)cron 环境,请将 set
放在脚本的开头。
关于bash - 使用 crontab 备份 Git Repo 的 Shell 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66621342/