Backup basics and sample scripts in Linux

This guide will provide a sample script for creating a backup of your Linux OS directories.Note: Feel free to edit variables from this script to fit your current environment


# How long script should keep backup?

# List of directories you want to backup - space separated
backup_files="/home /etc /root /boot"

# Desitnation directory of your backup (it could be a NFS)

# Create archive filename with date
day=$(date +%A)
hostname=$(hostname -s)

# Print start status message when backup script is running
echo "Backing up $backup_files to $dest/$archive_file"

# Backup the files using tar (and gzip).
tar czf $dest/$archive_file $backup_files

# Print end status message of backup script.
echo "Backup done"

# Delete older backup files older than 7 days

echo "Removing backup older than $days
find $dest -type f -mtime +$days -name '*.tgz' -execdir rm -- '{}' \;

Save this file with name eg. and put it into /usr/local/sbin directory

Next, allow execute this script:

$ chmod +x /usr/local/sbin/

Now you can add this script to crontab (please run this command as a root user):

$ crontab -e
Now you can paste this line inside your text editor:* 2 * * * /usr/local/sbin/ >/dev/null 2>&1

Save this file now. Your crontab has been updated, and your script will run daily at 2am.