In *nix, how to determine which filesystem a particular file is on?

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.


Solution 1:

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 of mount -v or similar.

Unfortunately, the output format of both df and mount are system-dependent; there is no apparent standard, at least as I can see between Solaris, NetBSD and Mac OS X.

Solution 2:

You could use stat. The command stat --printf '%d' filename.txt will return the device number as hex/decimal.

Solution 3:

For just a specific file it's as easy as

df -T "${FILE}" | awk '{print $2}' | tail -n1