Linux – Detecting that a device is mounted to a particular folder

backupblock-devicelinuxmount

As part of revamping my backup scheme, I'm now adding rotating external hard drives, keeping one safely off-site at all times while the other is receiving backup data. Naturally, to ensure that my backups actually get done, the backups will be scripted and cron'd.

My plan is to manually plug in and mount the hard drive, and then leave it there until it's time to unmount it (again manually), take it away, bring in the next one, and (manually) mount that one. Both drives would be mounted to e.g. /mnt/backup.

Now, here comes the question: I don't want the backup script to run if I forget to plug in or mount the hard drive. So I need to be able to detect if there is a device mounted to /mnt/backup before the script is allowed to run. My first thought is to put a file named e.g. 'NO_DRIVE_MOUNTED' in the (unmounted) /mnt/backup directory, and then make sure that that does not exist before running the backup routine, but that just feels hackish. (Likewise, the inverse of putting a file named e.g. 'BACKUP_DEVICE_READY' in each external hard drive and checking that that file does exist feels just as hackish.)

Is there a better way to detect whether or not a device is mounted to a given directory? I'd rather avoid checking for the device itself, as my experience is that plugging in a drive in Linux just assigns it to the next available /dev/sdX, so while the backup drive might be /dev/sdf one day, if I have a different drive plugged in when connecting the backup drive the next time it would be /dev/sdg, which means testing for /dev/sdf would fail! I'd also prefer to avoid device-specific identification (e.g. by UUID) so that I can more easily and more transparently replace/upgrade the drives.

This will be on Ubuntu 10.10 (or possibly 11.04 if I drag my feet long enough, as I'm in the process of rebuilding the whole server anyway), and ideally I'd like a simple one-line test that I can prefix to my backup command directly in my crontab (but I'm not afraid of Bash scripts, either, if that's what's necessary).

Best Answer

You may run your backup script like that in your cron

fgrep -q /mnt/backup /proc/mounts && backup.sh

But better add the test in your script, to log the failed attempts

Related Question