Qual è il modo migliore per verificare se due directory appartengono allo stesso filesystem?
Risposte accettabili: bash, python, C / C ++.
Qual è il modo migliore per verificare se due directory appartengono allo stesso filesystem?
Risposte accettabili: bash, python, C / C ++.
Risposte:
Può essere fatto confrontando i numeri di dispositivo .
In uno script shell su Linux può essere fatto con stat :
stat -c "%d" /path # returns the decimal device number
In pitone :
os.lstat('/path...').st_dev
o
os.stat('/path...').st_dev
Il comando standard df
mostra 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
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;
}
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)