두 개의 디렉토리 또는 파일이 동일한 파일 시스템에 속하는지 확인하는 방법 은 무엇인가요?

두 개의 디렉토리가 동일한 파일 시스템에 속하는지 확인하는 가장 좋은 방법은 무엇입니까?

허용되는 답변 : bash, python, C / C ++.



답변

장치 번호비교하여 수행 할 수 있습니다 .

Linux의 쉘 스크립트에서 stat 로 수행 할 수 있습니다 .

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

에서 파이썬 :

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

또는

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

답변

표준 명령 df은 지정된 파일이있는 파일 시스템을 보여줍니다.

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

답변

방금 Qt / C ++ 기반 프로젝트에서 동일한 질문을 보았고이 간단하고 휴대용 솔루션을 찾았습니다.

#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;
}

답변

“stat”답변은 가장 좋지만 두 파일 시스템이 동일한 장치에 있으면 오 탐지를 얻습니다. 여기까지 내가 찾은 최고의 Linux 쉘 방법이 있습니다 (이 예제는 Bash 용입니다).

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

(coreutils 8.21 이상 필요)