Search code examples
mysqllinuxcroncrontrigger

database and wordpress backup cron job


i want to run a cron job that back ups my mysql database and my wordpress files once a day from the hostgator cpanel.

i found a sample script and edited the parameters with my information but it doesn't seem to be working properly. I don't have much experience with cron jobs so i'm not sure what all my issues are.

i have the .sh file named, backups.sh, saved in the home directory and have a folder named backups with subfolders database and wordpress.

this is the .sh file. i replaced {my info} with my credentials and filled out everything for my database info:

#!/bin/bash
# Script Function:
# This bash script backups up the db everyday dependent on 
# when you set the cron job to run with a file name time stamp 
# and tar.gz zips the file.
# The db will be saved in /backups/database/
# Db backups older than 5 days will be deleted.\
#[Changes Directory]
cd /home/{my info}/backups/

#[Old DB Deletion and Files Script]
find /home/{my info}/backups/database -name "*.tar.gz" -mtime +5 -exec rm -f {};
find /home/{my info}/backups/wordpress -name "*.tar.gz" -mtime +5 -exec rm -f {};

#[Stamps the file name with a date]
TIMESTAMP=`date +%m-%d-%y-%H%M`

#[DB Backup Scripts]
# DB Name
HOST=localhost
DBNAME=""
USER=""
PASSWORD=""
DUMP_PATH=/home/{my info}/backups/database/
BACK_PATH=/home/{my info}/backups/wordpress/
mysqldump --opt -c -e -Q -h$HOST -u$USER -p$PASSWORD $DBNAME > $DBNAME.sql
tar czpf $DUMP_PATH/$DBNAME.$TIMESTAMP.tar.gz $DBNAME.sql

rm -f $DBNAME.sql
#Backing up Wordpress files @ root
tar czf $BACK_PATH/wordpress.$TIMESTAMP.tar.gz /home/{my info}/public_html/mydomain

Here is what I have for the command line:

/bin/sh ~/backups.sh

i get an email after the cron job executes and it notifies me saying, "No such file or directory", along with a bunch of command not found.


Solution

  • cron does not always have the same PATH variable as your login shell, and therefore cannot always locate the executable for things like mysqldump or even tar.

    I recommend using the full path to each command, ie: /usr/bin/mysqldump instead of just mysqldump. You can easily determine what the path is by using the which command.

    $ which mysqldump
    /usr/bin/mysqldump