In a generic, modern unix environment (say, GNU/Linux, GNU/Solaris, or Mac OS X), is there a good way to determine which mountpoint and filesystem-type a particular absolute file path is on?
I suppose I could execute the mount
command and manually parse the output of that and string-compare it with my file path, but before I do that I'm wondering if there's a more elegant way.
I'm developing a BASH script that makes use of extended attributes, and want to make it Do The Right Thing (to the small extent that it is possible) for a variety of filesystems and host environments.
The command
df(1)
takes one or more arguments and will return the mountpoint and device on which that file or directory exists, as well as usage information. You can then use the path or device to look up the filesystem type in the output ofmount -v
or similar.Unfortunately, the output format of both
df
andmount
are system-dependent; there is no apparent standard, at least as I can see between Solaris, NetBSD and Mac OS X.You could use stat. The command stat --printf '%d' filename.txt will return the device number as hex/decimal.
For just a specific file it's as easy as
Hm. For the mount point, you can go up the hierarchy until the st_dev changes (then you have just crossed over a mount boundary); there's GNU
stat
for bash scripts; however, I don't know how you can guess the filesystem type without parsing/proc/mounts
or by trial and error (i.e. handle failures after setting extended attributes)One gotcha with using
df
is that if the device name in the output is long it's line will wrap so you can't just grab the last line. Instead strip off the first line and then grab the new first line and then print the first field:There seems to be a catch with df and btrfs on Linux. When you ask df to locate the mount point for a mounted btrfs volume, it will do the right thing. In this case, joe is a sub-directory of /m/whale/backup.
But if the directory being referenced is a sub-volume, it won't tell you the mount point anymore.
The /a/whale/backup is the only mount point according to the kernel.
FWIW, stat does the same thing:
From https://stackoverflow.com/questions/2167558/give-the-mount-point-of-a-path:
works everywhere I have tested, for both *BSDs and sysVs, and for wacky automounted directories. I'd be delighted to hear of a case where it fails.