我的目标是每天备份我保存在 /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
的顶部,我将在 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上的远程仓库没有影响。
答案 0 :(得分:2)
在简化的环境下运行你的脚本,比如
env -i HOME=$HOME ./backup_notes.sh
您可能会发现脚本应该设置 PATH
或其他一些在 cron 环境中找不到的变量。要检查(相当有限的)cron 环境,请将 set
放在脚本的开头。
答案 1 :(得分:0)
我编写的脚本无法将 git repo 的内容推送到 github
为 crontab 设置路径和外壳 - How to get CRON to call in the correct PATHs
为相关存储库设置 SSH - git remote set-url origin git@github.com:USERNAME/REPONAME.git
参见:https://gist.github.com/developius/c81f021eb5c5916013dc
有用的调试技巧:
echo "Some text" > log.txt
h<my command> 2>&1 | tee -a log.txt
捕获错误和命令输出,例如 git pull origin main 2>&1 | tee -a log.txt