git commit 在 cron 作业中不起作用,尽管 git pull 确实有效

git commit doesn't work from a cron job, although git pull does work

在我的 crontab 中,我有以下行:

48 14 * * * bash /home/erelsgl/git/erel-sites/add-commit-push.bash "from home" 2&>1 >> /home/erelsgl/logs/backup_from_home.log

该脚本的作用如其名——添加、提交和推送:

DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
cd $DIR
echo --------------------
date
echo == add ==
/usr/bin/git add -A
echo == commit ==
/usr/bin/git commit -m ""
echo == pull ==
/usr/bin/git pull
echo == push ==
/usr/bin/git push

如日志文件所示,"commit" 不执行任何操作,而 "pull" 正常工作:

Fri Oct 23 14:48:01 IDT 2015
== add ==
== commit ==
== pull ==
Already up-to-date.
== push ==

我 运行 一分钟后从命令行执行完全相同的命令,并得到以下日志,这意味着提交确实发生了:

Fri Oct 23 14:49:31 IDT 2015
== add ==
== commit ==
On branch master
Your branch is up-to-date with 'origin/master'.

nothing to commit, working directory clean
== pull ==
Already up-to-date.
== push ==

从 cron 作业提交的 运行 有什么问题?

注意:我也在测试文件中进行了实际更改的相同实验。我发现,确实,提交不是从 crontab 发生的(没有任何东西被推送到上游),而是从命令行发生的。

cron默认使用sh,所以试试,如“How to redirect output to a file from within cron?”中所述:

  • 没有'bash'
  • 2>&1结尾

即:

48 14 * * * /home/erelsgl/git/erel-sites/add-commit-push.bash "from home" >> /home/erelsgl/logs/backup_from_home.log 2>&1

并在您的 bash 脚本中放入 shebang directive:

#!/bin/bash
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
cd $DIR
...

另一种形式是使用 bash 命令行(如“Redirecting the output of a cron job”):

48 14 * * *  /bin/bash -l -c '/path/to/script >> ./log/my_log.log 2>&1'

After changing the order of redirection as recommended, my log file indeed shows a long error message saying:

Please tell me who you are. 
Run git config --global user.email "you@example.com" 
    git config --global user.name "Your Name" 
to set your account's default identity

I already did this in my account, but the cron job probably does not find the config file. How can I make it find the correct git config file?

cron 作业可能 运行 与另一个帐户(或 root):它的全局 git 配置 (~/.gitconfig) 将与您设置的不同使用您的用户帐户。

一个简单的解决方案是 repeat those git config (without --global) inside the target git repo:这将在 repo 本身中注册用户 ID,而不是依赖不跨帐户共享的全局配置。