Come verificare se due directory o file appartengono allo stesso filesystem


15

Qual è il modo migliore per verificare se due directory appartengono allo stesso filesystem?

Risposte accettabili: bash, python, C / C ++.


Se vuoi risposte python / C ++ sei nel sito sbagliato
Michael Mrozek

Buon punto - dovrei scrivere "Python, C / C ++ sono accettabili".
Grzegorz Wierzowiecki,

@MichaelMrozek ricorda che le domande dell'API C sono in tema: meta.unix.stackexchange.com/questions/314/…
Grzegorz Wierzowiecki

Risposte:



3

Il comando standard dfmostra su quale filesystem si trovano i file specificati.

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

3

Ho appena incontrato la stessa domanda in un progetto basato su Qt / C ++ e ho trovato questa soluzione semplice e portatile:

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

Libreria molto specifica, pesante e non standard.
Sandburg,

1

La risposta "stat" è più approfondita, ma ottiene falsi positivi quando due filesystem si trovano sullo stesso dispositivo. Ecco il miglior metodo di shell Linux che ho trovato finora (questo esempio è per Bash).

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

(richiede coreutils 8.21 o successivi)


Ciò richiede Coreutils 8.21 o successivo. ( commit che ha aggiunto la funzionalità) ( note di rilascio che riportano la funzionalità)
Keith Russell,
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.