This article is about running backup job only if destination mount point exists on the system. This script was tested on Ubuntu LTS 18 and 20. Both, desktop and server versions. You can get Ubuntu from here.

BASH script, Part One

I need to check if backup destination is mounted before backup job begins. Destination media can be external hard drive or NFS export on another server. One of they ways to accomplish this is to check for the mount point in /proc/mounts using grep command. The script will look like this:

#!/bin/bash

if grep -qs '/mnt/backup_drive' /proc/mounts;
then
rsync -a /home/eugene /mnt/backup_drive/
else
echo "Backup destination is not mounted."
exit 1
fi

This simple BASH if/then script will check for the mount point /mnt/backup_drive in /proc/mounts. If the mount point is there, it will run a backup job using rsync to copy data from /home/eugene to /mnt/backup_drive. If mount point is not found the script will display a message saying that “Backup destination is not mounted” and rsync command will not run. There is more that I could do with this script.

BASH script, Part Two

Let’s say that I also want to backup external drive that is connected to your laptop or desktop computer. I might not have it connected every time the job is running but I want it to be included when it is connected and mounted. At this point I would add another if/then to the script, like so:

if grep -qs '/media/eugene/external_drive' /proc/mounts;
then
rsync -a /media/eugene/external_drive /mnt/backups/
else
echo "Your external hard drive is not mounted"
exit 1
fi

In the example above my external hard drive is mounted in /media/eugene/external_drive. This part of the script will run right after the first part, so the destination mount point is already checked for. Assuming my destination stays the same for all your backups. If external hard drive is not mounted the script will stop and return “Your external hard drive is not mounted” message. This is a convenient way for scheduling one job and backing up multiple sources, if they are available. Please note that if the destination is not mounted the script will exit before it gets to the second part.

As always, I hope you found it useful. Edit the script’s mount points, source and destinations to fit your needs. Enjoy!