Ubuntu – Setup CRON weekly backup


I want to make a backup of my /var/lib/mysql and /var/www folders and save them as tar.gz files to my mounted network file server (uslons001).

Here is my bash file located in: /bin/backups/mysqlbackup.sh

mkdir /home/lv_admin/uslons001/`date +%d%m%y`
cd /home/lv_admin/uslons001/`date +%d%m%y`
tar -czf mysql.tar.gz /var/lib/mysql
tar -czf www.tar.gz /var/www

Which works PERFECTLY fine when I execute it in a cmd shell but when I setup the cron job it never runs, so I'm not setting the cron job up properly. My cron job looks like this.

   36 10 * * 5 /bin/backups/mysqlbackup.sh

..there is also nothing in the /var/log/cron.log file, so no errors are being logged. (even after enabling cron logging in the /etc/syslog.conf file

Best Answer

Few points to make:

  • Why are you using timestrings in /etc/cron.weekly/ scripts at all? You're only supposed to put executable scripts in there. You don't need to crontab them or anything else. That will just duplicate their work. Look at /etc/cron.daily/apt for an example of what I'm talking about. It's just a plain script.

  • Per geirha's comment, the file can't have an extension. Odd, I know, so rename it:

    sudo mv /etc/cron.weekly/mysqlbackup{.sh,}
  • You need to run sudo chmod +x /etc/cron.weekly/mysqlbackup to make it executable. You can then test it by running it, using that path.

  • If you leave it in /etc/cron.weekly/, the script is going to run as root. None of your ~/ links are going to work. Use full paths. I'd suggest that after you do the mkdir you cd into it and that will reduce the huge paths in subsequent commands. If you need the generated files to be owned by your user, make your script chown them to your user when it's done backing up.

    I don't see any reason for any of this to be root driven. You could plonk the script in your home directory and just use the standard crontab -e to add your rule and have it run. It still needs to be executable and I'd still recommend you use full paths, but it keeps the permissions slightly easier.

Related Question