Cron 作业自动推送到 Git 问题

Cron job Auto-Push to Git Issue

我有一个 cron 作业设置 运行 一个 bash 脚本每晚推送到 Git。

cron 作业设置为 root,我已经通过以下方式设置了我的 git 凭据:git config credential.helper store 根据:Git push: username, password, how to avoid?(第二个答案)

bash脚本的代码非常简单

#!/bin/bash

# Nightly push to Bitbucket

# Set some variables
DAY=$(date +%F);

# Make sure we run as root
if [ "$(whoami)" != "root" ]; then
    echo "Only root can do this.";
    exit 1;
else
    # Make sure we are in the right directory
    cd /hosting;
    # Now add any changes
    git add .;
    # Now commit
    git commit -m "$DAY Nightly";
    git push all;
fi;

并且 运行 只要我登录到服务器并 运行 以 root 身份登录,就不会出现问题。

但是,它没有在指定的时间运行。

crontab -e 设置为:30 3 * * * back-to-git >/dev/null 2>&1

我该怎么做才能让它发挥作用?

首先,最好在 cron 选项卡中包含脚本的 完整 路径。

30 3 * * * /opt/btg/back-to-git >/dev/null 2>&1

/opt/btg/back-to-git 替换为您的脚本的绝对路径。 然后尽量不要丢弃我包含错误的输出:

30 3 * * * /opt/btg/back-to-git &>/home/your_user/btg.log 

这样您就可以在 cron 处理脚本时检测到错误。

您最后的评论表明 bitbucket 可能存在身份验证问题。为了确保您以正确的方式推进,我建议始终在脚本中写出 git 的完整目标。所以尝试使用

git push --all origin 而不是 git push all;

请检查您的 git 设置,以便在推送到 bitbucket 时使用 ssh 而不是 https

您还可以指定要在 /root/.ssh/config

中使用的主机和 ssh 密钥
Host bitbucket
  HostName bitbucket.org
  User YOUR_USERNAME
  IdentityFile /root/.ssh/id_rsa
  IdentitiesOnly yes