How to bind-mount a single file

A few days ago, while working on a cool feature for the Ubports project, I met the need to bind-mount a single file into a new directory. While I had used bind-mounts many time before, I always had to deal with directories, and I erroneously assumed that mounting a single file would work in the same way:

$ sudo mount -o ro,bind myfile destdir/

But it doesn't; instead, I got this nice error message:

mount: mount(2) failed: Not a directory

Now that I know what the issue was, the error message seems quite obvious and explicative; but I swear that at the time when I first saw it, I didn't help me at all and I found myself searching for it online, with little luck. Eventually I found the solution to the problem, which, after all, seems pretty logical: when bind-mounting a single file, the destination mount point must also be a regular file.

That is, I should have done:

$ touch destdir/myfile
$ sudo mount -o ro,bind myfile destdir/myfile

I'm leaving it here, in case someone hits this page from a search engine out of despair. :-)

Comments

There's also webmention support.