Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

git

crontab

In my crontab, I have the following line:

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

The script does what its name implies - add, commit and push:

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

As seen in the log file, the "commit" does nothing while the "pull" works fine:

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

I ran the exact same command, a minute later, from the command line, and got the following log, which means that the commit did happen:

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 ==

What is the problem in running commit from a cron job?

NOTE: I also did the same experiment with an actual change in a test file. I found out that, indeed, the commit didn't happen from the crontab (nothing was pushed to upstream) but did happen from the command line.

like image 798
Erel Segal-Halevi Avatar asked Oct 23 '15 11:10

Erel Segal-Halevi


1 Answers

cron uses sh by default, so try, as described in "How to redirect output to a file from within cron?":

  • no 'bash'
  • with 2>&1 at the end

That is:

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

And put in your bash script a shebang directive:

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

Another form would be to use a bash command line (as in "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 "[email protected]" 
    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?

The cron job is likely to run with another account (or root): its global git config (~/.gitconfig) won't be the same as the one you set with your user account.

One simple solution is to repeat those git config (without --global) inside the target git repo: that will register the user id in the repo itself, instead of relying on a global config which is not shared across accounts.

like image 105
VonC Avatar answered Nov 02 '22 19:11

VonC