15

What's the best way to check if two directories belong to the same filesystem?

Acceptable answers: bash, python, C/C++.

25

It can be done by comparing device numbers.

In a shell script on Linux it can be done with stat:

stat -c "%d" /path  # returns the decimal device number 

In python:

os.lstat('/path...').st_dev

or

os.stat('/path...').st_dev
| improve this answer | |
3

The standard command df shows on what filesystem the specified file(s) is located.

if df -P -- "$1" "$2" | awk 'NR==2 {dev1=$1} NR==3 {exit($1!=dev1)}'; then
  echo "$1 and $2 are on the same filesystem"
else
  echo "$1 and $2 are on different filesystems"
fi
| improve this answer | |
3

I just came across the same question in a Qt / C++ based project, and found this simple and portable solution:

#include <QFileInfo>
...
#include <sys/stat.h>
#include <sys/types.h>
...
bool SomeClass::isSameFileSystem(QString path1, QString path2)
{
        // - path1 and path2 are expected to be fully-qualified / absolute file
        //   names
        // - the files may or may not exist, however, the folders they belong
        //   to MUST exist for this to work (otherwise stat() returns ENOENT) 
        struct stat stat1, stat2;
        QFileInfo fi1(path1), fi2(path2),
        stat(fi1.absoluteDir().absolutePath().toUtf8().constData(), &stat1);
        stat(fi2.absoluteDir().absolutePath().toUtf8().constData(), &stat2);
        return stat1.st_dev == stat2.st_dev;
}
| improve this answer | |
  • Very specific library, heavy and not standard. – Sandburg Oct 23 '19 at 7:09
1

The "stat" answer is tersest, but it gets false positives when two filesystems are on the same device. Here is the best Linux shell method I've found so far (this example is for Bash).

if [ "$(df file1 --output=target | tail -n 1)" == \
     "$(df file2 --output=target | tail -n 1)" ]
    then echo "same"
fi

(requires coreutils 8.21 or newer)

| improve this answer | |
  • This requires Coreutils 8.21 or newer. (commit that added the feature) (release notes that report the feature) – Keith Russell Jun 30 '17 at 14:57
  • How can two file systems be on the same device? I'm wondering whether this is a real-life issue, or rather an obscure corner case. – Ingo Karkat Aug 6 at 14:47
  • Believe it or not, it’s common, especially on home Linux installations. Regardless of OS, many filesystem devices, including all hard drives, may be “partitioned”, and each partition formatted as a separate filesystem. This has been the case for decades. In fact, in traditional contexts, a filesystem can only live on a partition. But nowadays, there are fancy multi-partition filesystems such as RAID. In any case, filesystems do not directly live on the device layer, for most types of device. – Keith Russell Aug 7 at 12:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.