Testing whether a file is local

mountnetworkingtest

I need to test in a script, whether a file is from a network mount or truly local. To be more clear: I need to test, whether parsing the contents will be fast or slow, but for my case local vs network is a reliable indicator.

The best attempt I've come up with is stat -c %m [path] to get the mount point for the path, which gives / for files on my local disk and the mounting point for a CIFS mount.

But I suspect that this isn't a reliable diagnostic beyond my very simple config (one local drive, one big partition, a couple of network mounts) so I'd like a robust/canonical approach. Searching hasn't given any useful leads; terms like “network” and “path” are just too overloaded.

Best Answer

You can output the type of the filesystem that contains a given file or directory using

 stat -f --format="%T" /path/to/file

and take action based on that. Some possible outputs are cifs, nfs, afs, … (presumed remote) and ufs, ext2/ext3 (sic - ext2, ext3, and ext4 have the same filesystem magic number), btrfs, tmpfs, … (presumed local).

One thing that can help you decide if a filesystem type is local or remote: GNU coreutils, which includes stat and df, has a notion of "local" and "remote" filesystem for a few dozen different filesystem types.

df -T -l | awk 'NR > 1 { print $2 }' | sort -u

will output the filesystem types of all mounted filesystems that df believes are local.

As pointed out in the comments on the original question, it is difficult to tell whether a storage device is local; an ext3 filesystem on /dev/sdb5 could be on a fibre channel device, which could be directly attached or could be several network switches away, which you are unlikely to be able to discern using standard user-level utilities.

Related Question