Prevent the possiblity of writing data to an unmounted mount point directory [duplicate]

I have an Ubuntu server where I'm automounting an external hard drive each boot.

To do this, I've created an empty folder on the root partition, and the drive gets mounted "inside" this folder.

However, what if I perform a backup to this path when the drive isn't properly mounted? The backup would instead fill up my root partition!

I can ensure that the drive is mounted each time by performing:

sudo mount -a

... before each backup.

However, what are the best practices to ensure that data is never written to the empty mount-folder (except when the external hard drive is truly mounted)?

Can this be solved without scripting? Say with permissions for example? What are the best practices?


I go a step further and always set the attributes of my mountpoint directories to immutable using chattr.

This is accomplished with chattr +i /mountpoint (with the mount unmounted).

This would error-out on new write activity and also protects the mount point in other situations.

But I suppose you could use the mountpoint command, too ;)


To expand on the comment about using mountpoint, this is roughly what I put into scripts when I need to check these kind of things:

DEST='/mnt/backup'
if ! mountpoint -q "$DEST" ; then
    echo "Destination is not mounted; attempting to mount"
    mount $DEST
    if ! mountpoint -q "$DEST" ; then
        echo "Unable to mount $DEST; Aborting"
        exit 1
    fi
    echo "Mounted $DEST; Continuing backup"
fi

This assumes that $DEST exists in /etc/fstab; it doesn't matter if it is an auto or noauto mountpoint.

As per the mount man page:

If only directory or device is given, for example:

mount /dir

then mount looks for a mountpoint and if not found then for a device in the /etc/fstab file. It's possible to use --tar‐get or --source options to avoid ambivalent interpretation of the given argument. For example

mount --target /mountpoint