git commit在cron作业中不起作用,虽然git pull确实有用

时间:2015-10-23 11:12:21

标签: git crontab

在我的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 "$1"
echo == pull ==
/usr/bin/git pull
echo == push ==
/usr/bin/git push

如日志文件中所示,“提交”不执行任何操作,而“拉”工作正常:

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上(没有任何内容被推送到上游),但确实是从命令行发生的。

1 个答案:

答案 0 :(得分:7)

默认情况下,

cron使用sh,请尝试按照" How to redirect output to a file from within cron?"中所述:

  • no' 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'
  

按照建议更改重定向顺序后,我的日志文件确实显示一条很长的错误消息:

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
  

我已经在我的帐户中执行了此操作,但是cron作业可能找不到配置文件。如何让它找到正确的git配置文件?

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

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