How to add a bash script to a cron job?

I have a script called backup.sh:

#!/bin/bash
sudo zip -r /home/jazuly/backup.zip /var/lib/automysqlbackup/
cd /home/jazuly/backupscript/cp2google/
php cp2google.php /home/jazuly/backup.zip
cd ~
rm -f /home/jazuly/backup.zip

I made it executable:

sudo chmod +x backup.sh

Then I tried to edit cronwith crontab -e.

I add:

# m h dom mon dow command
0 0 * * * /home/jazuly/backup.sh

but when cron sends the backup.zip to my email, I download and open it, and the file is corrupt.

If I run the script manually with:

$ sudo chmod +x backup.sh
$ ./backup.sh

I can open the zip file.

7

3 Answers

You will need to use the full path in any cron executed script. So, don't do cd ~, give instead cd /home/jazuly

For further debugging, you can also redirect the output of the cron script to a file, with /home/jazuly/backup.sh 1> /home/jazuly/log.txt 2> /home/jazuly/err.txt

So the whole command:

# m h dom mon dow command
0 0 * * * /bin/bash /home/jazuly/backup.sh 1> /home/jazuly/log.txt 2> /home/jazuly/err.txt
17

Try to use full paths

#!/bin/bash
/usr/bin/zip -r /home/jazuly/backup.zip /var/lib/automysqlbackup/
/usr/bin/php /home/jazuly/backupscript/cp2google/cp2google.php /home/jazuly/backup.zip
rm -f /home/jazuly/backup.zip

And add /bin/bash in cron

# m h dom mon dow command
0 0 * * * /bin/bash /home/jazuly/backup.sh

And check permissions for files backup.zip, backupdatabaseterbaru-c771cd4f4fcf.p12

4

Here are the steps of how I fixed it:

  1. Change Permission & Owner of var/lib/automysqlbackup to 777 & jazuly.jazuly.
  2. Move all the folders & files from backupscript/cp2google/ to home/jazuly.
  3. Use wait for every statement.
  4. My final code:

    #!/bin/bash
    zip -r backup.zip /var/lib/automysqlbackup/
    wait
    php cp2google.php backup.zip
    wait
    rm -f backup.zip

    And my cron:

    0 0 * * * /home/jazuly/backup.sh

    to backup every midnight/day.

    I don't think there is a need to write the full path if the .sh file is in the same path with what you want to execute.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like