Create a loop in a Linux filesystem

suresh picture suresh · Apr 8, 2009 · Viewed 9.9k times · Source

How do I create a loop in the Linux filesystem? I want to break the directed acyclic graph (DAG) property of the Linux filesystem. Is this possible? I have seen this condition once when I installed the scratchbox cross compiler on my Ubuntu.

I don't know how to reproduce it now.

Answer

Eric Melski picture Eric Melski · Apr 8, 2009

Some other responders have already answered how to set up a mount using the loopback device, but you specifically asked about bind mounts, which are a little bit different. If you want to use a bind mount, you just specify --bind in the mount command. For example:

mount --bind /original/path /new/path

This will make the filesystem location accessible at /original/path also accessible through /new/path. Note that this will not following mountpoints! For example, suppose I have the following mountpoints:

/something
/something/underneath/that

Now suppose I make a bind mount for /something:

mount --bind /something /new_something

I will be able to access files like /something/myfile via the path /new_something/myfile. But I will not be able to access files like /something/underneath/that/otherfile via the path /new_something/underneath/that/otherfile. You must set up a separate bind mount for each filesystem; or if you have a relatively new kernel, you can use rbind mounts, which do follow mountpoints:

mount --rbind /something /new_something

One caveat about rbind mounts: they do not handle the case where a filesystem is mounted after the rbind is setup. That is, suppose I have a mount like this:

/something

Then I set up my rbind as above, and then I mount /something/underneath/that: the rbind will not magically make the new mount visible through the rbind location. Also be aware that apparently due to a bug in the kernel, you cannot unmount an rbind mount.

Also, just in case you meant "How do I set up bind mounts using the mount(2) system call?": you must specify the MS_BIND flag (defined in mount.h) when you call mount(2) for a regular bind mount. For an rbind mount, you must specify MS_BIND and the undocument MS_REC flag (defined in linux/fs.h).

Hope that helps,

Eric Melski