If you have a Linux machine with different mounts, especially remote ones, you might have found yourself in a position where the mount failed and files written to the mount point filled up your boot drive or similar. Perhaps you have thought to yourself “it would be super nice to be able to make sure files can’t be written to this mount point if it’s not actually mounted”. I myself mount a Google Drive using rclone and even though it works fine 99% of the time it was a headache when you all of a sudden had a network issue during mount, the mount failed and you wrote hundreds of gigabytes to the folder that was the mount point. Especially since those files are “hidden” when you mount your filesystem on top of it.
But through the years I have found that there is a way, or at least a work around, to achieve the “only write if mounted” protection.
The “solution” is to use chattr to change the file attributes of the folder you use as your mount point. By setting chattr -i you make it so that the folder cannot be modified, it cannot be deleted or renamed, no link can be created to the folder, most of the folder’s metadata can not be modified and the folder can not be opened in write mode.
What this does is that it ensures that no files trying to be written to the folder will succeed. But, ant this is the crucial part that make it all work, you can still use it as a mount point. So if/when you have mounted something to that path you will be able to access that mount and write to it as normal. But if the mount for any reason fails or simply hasn’t been done any attempt to write to the folder will result in an error.
Note that only the superuser or a process possessing the CAP_LINUX_IMMUTABLE capability can set or clear this attribute.