21

One of my scripts dynamically creates a symlink like so:

ln -s /home/hosting/projects/images /home/hosting/projects/demo/images

How can I make it so that the access through link is read-only?

Eliah Kagan
  • 116,445
  • 54
  • 318
  • 493
Elmor
  • 345
  • 1
  • 3
  • 15

2 Answers2

23

You can create a read-only bind-mount.

mount --bind /path/to/source/ /path/to/dest/
mount -o bind,remount,ro /path/to/dest

Yes, this must be done in two steps in kernels after Linux kernels 2.6.25 (see the link above for why).

Or, alternatively, as an /etc/fstab line example ref:

/path/to/source/ /path/to/dest/ none bind,ro

In either approach, a bind mount lives in the Virtual Filesystem layer (VFS), so this it's not specific to any filesystem, nor do you really 'mount' anything. So, basically, this is creating a sort of symbolic link for you, but this doesn't show up as such.

And to reply on the comment below on data loss... no, these instructions do not remove any files. In case you have files present on the destination path, this mount will lay over this. Just unmount to be able to list your files in the path on the filesystem underneath. Even better; in general, avoid mounting on top of an non-empty destination path.

gertvdijk
  • 67,007
  • 33
  • 188
  • 283
  • 1
    Be careful. Followed these steps and it removed my whole backup directory and made it not writable by my backup daemon. –  Jan 03 '14 at 10:17
  • can you please provide this solution as an fstab entry? – Throoze Jan 15 '16 at 11:14
  • 1
    @Throoze There you go ;) – gertvdijk Jan 16 '16 at 20:08
  • The remount command should probably be: `mount -o bind,remount,ro /path/to/dest` See http://lwn.net/Articles/637501/ from that same thread. –  Aug 22 '16 at 15:54
  • `mount -o remount,ro /path/to/dest` gives me the following error: `mount: mount point is busy.` @gertvdijk – alper May 23 '19 at 07:34
  • @alper Well, yeah, then you have applications/processes still using files on that source or mountpoint. Use lsof/ss or other tooling to find out what's still having files open on it. – gertvdijk May 23 '19 at 10:37
  • @LeviBlackstone fixed, thanks. (sorry just only noticed this almost three years later...) – gertvdijk May 23 '19 at 10:38
5

to mount bind readonly with one command:

mount --bind -r /path/to/source/ /path/to/dest/

to unmount

umount /path/to/dest/
Shimon Doodkin
  • 251
  • 3
  • 5