Task: Create a Cronjob that executes a bash script once every night. The bash script should do a mongoDB Backup and push it to a Git Repo.

So I created a cronjob as the root user via the crontab -e command:


0 2 * * * /path/script.sh > /path/script.log

This is the script that should be executed:



echo "starting backup"
echo $BAK
/usr/bin/mongodump --username=myusername --password=mypassword --db=mydatabase --out=$BAK$
echo "backup created"
/usr/bin/git add .
/usr/bin/git commit -m "backup from `date +'%Y_%m_%d'`"
echo "committed"
/usr/bin/git push -u origin master
echo "pushed backup. done"

Outcome: Backups are being created but not pushed to the repo. Executing the script manually pushes the backups as desired. The Log only includes all the echos from the script.

  • make sure you're in the right directory when the cron job is executed. Maybe add a cd directive to be sure or change the git add . to git add /your/full/path – Pierre-Alain TORET Nov 16 '15 at 12:42
  • 1
    To me it feels like a bad idea to store database dumps in a git repository. Check this programmers exchange Q&A for explanation. – Henrik Pingel Nov 16 '15 at 14:48

You need to change directory to "$BAK" before issuing the git commands.

You explicitly write your backups to $BAK$ but when you run the gid add . you will be in the home directory of the user that is running the cron job. In this case that will be /root.

Here is a test script

pwd >/tmp/atest.out
touch ./atest.file

When run from root's crontab with

* * * * * /home/iain/atest

The contents of /tmp/atest.out


So where is ./atest.file

ls -l /home/iain/atest.file
ls: cannot access /home/iain/atest.file: No such file or directory


ls -l /root/atest.file
-rw-r--r--. 1 root root 0 Nov 16 13:24 /root/atest.file

Bingo!. It does not matter that you are running the script from git's home directory. The working directory is in this case is /root.

/usr/bin/git add .

is adding the current working directory, which unless you have changed it is /root.

  • the script is in the gits root directory. so that does not solve it – Martin Golpashin Nov 16 '15 at 12:57
  • How's about you actually make the change I suggest, then come back and thank me for solving your problem. – Iain Nov 16 '15 at 13:08
  • I already tried it out and it does not work. Thank you though for the attempt though – Martin Golpashin Nov 16 '15 at 13:13
  • Then there is something you are not telling us. It really is the solution to the problem described. – Iain Nov 16 '15 at 13:16

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.