Is there anyway to automatically mount a filesystem when I open a symbolic link to a directory on that filesystem?

autofs can do this for you. You can configure any number of mountpoints with various options, and the corresponding filesystems are mounted whenever the mountpoint is accessed. After a given amount of inactivity the filesystems are unmounted again.

There are no doubt various ways of using autofs, but here's one way of doing what you're trying to do, based on the way I used to use it.

You start with a directory which will hold a number of autofs mount-points (well, at least one); say /misc. You don't need to create it, but you do need to create a configuration file which will describe all the filesystems you want to mount there; for example, I could mount CDs, DVDs and Blu-Rays with the following file, saved as /etc/auto.misc:

cd              -fstype=iso9660,ro,nosuid,nodev    :/dev/cdrom
br              -fstype=udf,ro,nosuid,nodev        :/dev/cdrom

The general syntax is the mountpoint, followed by any options introduced by -, then the mountpoint introduced by : on a local system. (I'm simplifying here, see the autofs(5) manpage for details.)

Then this file is enabled by adding an entry in /etc/auto.master:

/misc   /etc/auto.misc

Restart autofs with

sudo service autofs restart

and you should be able to run

ls /misc/cd

and see the contents of any CD in your drive. (Obviously replace the name and mount target by whatever is appropriate in your case.)

Once you have that, you can link to anything in the auto-mounted filesystems from anywhere else, in the same way as if they were standard, non-auto-mounted filesystems. So in my example,

ln -s /misc/br blu-ray

creates a blu-ray link wherever the command is run. You can link further into the filesystem as well,

ln -s /misc/br/BDMV autolinktest

creates an autolinktest link to the movie contents. Accessing the links will mount the target filesystem.


You can do this with systemd, so you don't have to install extra software and just have a small amount of extra configuration.

Simply add noauto,x-systemd.automount to the options in fstab.

noauto to not mount automatically on boot and x-systemd.automount to let systemd mount it on access.

After adding x-systemd.automount to an fstab line, you need to run:

  sudo systemctl daemon-reload

And then one, or both, of the following:

  sudo systemctl restart remote-fs.target
  sudo systemctl restart local-fs.target

Then the automount will become active and usable.

Source: ArchWiki - fstab