1

So i created a script used to backup system, i tested and it worked. Here's the script:

#!/bin/bash
backup_files="/home /var/spool/mail /etc /root /boot /opt"
dest="/mnt/backup"
day=$(date +%F)
hostname=$(hostname -s)
archive_file="$hostname-$day.tgz"
echo "Backing up $backup_files to $dest/$archive_file"
date
echo
tar czf $dest/$archive_file $backup_files
echo
echo "Backup finished"
date
ls -lh $dest

But when put it in crontab , it didn't work. I used "crontab -e" and put this following command line in there

* * * * * /root/backup_system.sh

I waited and nothing happend. I don't know where i was wrong. @I'm running Ubuntu 14.04, the script was changed permission using chmod.

  • Don't set it to run with * * * * *. Otherwise a new copy will be spawned every minute, whether or not the previous instance has completed. This can lead to output files being overwritten or corrupted by interpolation. – roaima May 30 '16 at 10:01
  • @roaima Thank you for your advice. I just use that for testing purpose^^ – The One May 31 '16 at 0:59
2

Unless your script is not executable (fix that with chmod +x /root/backup_system.sh) or the crond isn't running, there's nothing obviously broken in your script that will prevent it from running.

All of the commands you use (date, hostname, tar, and ls) should be in /bin, which should be in the default PATH....unless you've changed it in your crontab.

The most likely explanation is that you're trying to run this script from a user's crontab rather than root's crontab. And that user doesn't have read and execute access to the /root directory or to the /root/backup_system.sh script.


BTW, you should always double-quote your variables. And it's a good idea to use an array variable for variables that contain a list of things (like $backup_files).

Here's an improved version of your script which fixes those problems:

#!/bin/bash

backup_files=(/home /var/spool/mail /etc /root /boot /opt)
dest='/mnt/backup'
day=$(date +%F)
hostname=$(hostname -s)
archive_file="$dest/$hostname-$day.tgz"

echo "Backing up ${backup_files[@]} to $archive_file"
date
echo

tar czf "$archive_file" "${backup_files[@]}"

echo
echo "Backup finished"
date

ls -lh "$dest"

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.