bash - 使用 crontab 备份 Git Repo 的 Shell 脚本

标签 bash git shell github cron

我的目标是备份我保存在 /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/

相关文章:

bash - 简单的 bash 和 curl 检查 Web 服务器上是否存在文件?

git - 为什么 `git submodule` 每次都需要从远程存储库中获取?

git - 从旧存储生成补丁文件

windows - Jenkins 没有从 Windows 凭据管理器中检测到 GIT 凭据

php - 如何在单个 shell 行中执行多个 PHP 文件?

linux - 为什么 grep 不在此 shell 脚本中使用我的变量?

linux - bash:从给定子目录名称的当前目录获取路径

mysql - 在 Bash 脚本中获取更新的 MySQL 日期

linux - 如何创建备份脚本来比较日期和删除最旧的文件

python - 填满磁盘空间最快的方法是什么