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...
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.
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
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
Here are the steps of how I fixed it:
- Change Permission & Owner of
var/lib/automysqlbackupto777&jazuly.jazuly. - Move all the folders & files from
backupscript/cp2google/tohome/jazuly. - Use
waitfor every statement. My final code:
#!/bin/bash zip -r backup.zip /var/lib/automysqlbackup/ wait php cp2google.php backup.zip wait rm -f backup.zipAnd my
cron:0 0 * * * /home/jazuly/backup.shto backup every midnight/day.
I don't think there is a need to write the full path if the
.shfile is in the same path with what you want to execute.