Skip to main content

One of the simplest ways to backup a system is using a shell script. For example, a script can be used to configure which directories to backup, and pass those directories as arguments to the tar utility, which creates an archive file. The archive file can then be moved or copied to another location. The archive can also be created on a remote file system such as an NFS mount.

#!/bin/sh
####################################
#
# Backup to NFS mount script.
#
####################################

# What to backup.
backup_files="/home /var/spool/mail /etc /root /boot /opt"

# Where to backup to.
dest="/mnt/backup"

# Create archive filename.
day=$(date +%A)
hostname=$(hostname -s)
archive_file="$hostname-$day.tgz"

# Print start status message.
echo "Backing up $backup_files to $dest/$archive_file"
date
echo

# Backup the files using tar.
tar czf $dest/$archive_file $backup_files

# Print end status message.
echo
echo "Backup finished"
date

# Long listing of files in $dest to check file sizes.
ls -lh $dest

####################################
#
# Restore Backup Commands
#
####################################

# Show a listing of the archive contents
tar -tzvf /mnt/backup/host-Monday.tgz

# Restore a file from the archive to a different directory
tar -xzvf /mnt/backup/host-Monday.tgz -C /tmp etc/hosts

# Restore all files in the archive
cd /
sudo tar -xzvf /mnt/backup/host-Monday.tgz