2

This is my script, backup_mongo.sh

#!/bin/bash
suffix=$(date +%w)
rm /home/myuser/backup/mongo-$suffix -rf
mkdir /home/myuser/backup/mongo-$suffix
mongodump -h$1 -u$2 -p$3 -dmydb -o/home/myuser/backup/mongo-$suffix

In my crontab -e:

0   3  *   *   *    /bin/bash  /home/myuser/myproject/production/backup_mongo.sh  localhost user1 pass1

When I run the script normally (executing the command above), the script works and the directory "mydb" gets created in /mongo-$suffix.

However, when I put this in crontab, /mongo-$suffix gets created but the "mydb" directory does not exist. There's nothing in /mongo-$suffix.

3 Answers 3

4

You may not have mongodump in your PATH. Try using the absolute path to the mongodump command.

2
  • If I log in as "myuser", and I just run mongodump, it works. And also, I did put it in /etc/profile. PATH=$PATH:/opt/mongodb/bin export PATH
    – Alex
    May 15, 2011 at 20:25
  • 5
    Try doing exactly what this answer suggests, putting the full path in the script, or at least execute it as $(which mongodump). Your cron may not be loading anything from your profile.
    – Caleb
    May 15, 2011 at 20:41
2

It is very likely a PATH issue but I would recommend to NOT override PATH in your crontab, because it is

  • really easy to avoid the behavior
  • may be a security risk

Its good bash/sh coding style to define every binary that you want to trigger with with it's full path as variable

!#/bin/bash

RSYNC="/usr/bin/rsync"

and refer to the variable later.

$RSYNC /foo/bar baz

There are also certain options to change the user that is executing the crontab. Assuming that there is a user called mongodump that has defined a PATH that includes mongodump, you could become this user and edit it's crontab. Or you could also use

/bin/bash /bin/su - mongodump -c /bin/bash /home/myuser/myproject/production/backup_mongo.sh

in roots's crontab.

1

The default PATH for cron is restricted. It is usually /usr/bin:/bin. If you want to run anything outside of those directories you have several options

Use full paths to the commands e.g. /path/to/mongodump/mongodump ...

Define an extended PATH in the crontab e.g.

    PATH=/usr/bin:/bin/:/path/to/mongodump
    0 3 * * * /bin/bash  /home/myuser/myproject/production/backup_mongo.sh  localhost user1 pass1

Define the PATH in the script you are running

#!/bin/bash
PATH=/usr/bin:/bin:/paath/to/mongodump
suffix=$(date +%w)
rm /home/myuser/backup/mongo-$suffix -rf
mkdir /home/myuser/backup/mongo-$suffix
mongodump -h$1 -u$2 -p$3 -dmydb -o/home/myuser/backup/mongo-$suffix

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .