Check if two files are on the same level in bash

Is there a way to check if two files are on the same volume in bash on Mac OS X? Or, equivalently, to check if the given file is on the boot volume?

I've tried using ln

and checked to see if it works, but sometimes ln

fails for reasons other than error cross-device link

.

I also tried using a function that prints the file path and then checks to see if that path contains /Volumes/

a prefix, but not all of my remote volumes connect to /Volumes/

.

Is there another way?

+3


source to share


2 answers


You are asking if the two files are on the same filesystem. The canonical way to test this is to call a system call stat()

on two files and check if they have the same value st_dev

, where st_dev

identifies the device that the file is on.

You can use a command stat

in bash to do this test:

device=$(stat -f '%d' /path/to/file)

      



So, to check if two files are on the same filesystem:

dev1=$(stat -f '%d' /path/to/file1)
dev2=$(stat -f '%d' /path/to/file2)

if [ "$dev1" = "$dev2" ]; then
    echo "file1 and file2 are on the same filesystem"
fi

      

The above works are done under OS X; the same check can be done on Linux, but the command stat

requires -c

or --format

instead of -f

.

+7


source


From df

:



f1="$(df -P /path/to/file1.txt | awk 'NR!=1 {print $1}')"
f2="$(df -P /path/to/file2.txt | awk 'NR!=1 {print $1}')"

if [[ "$f1" = "$f2" ]]; then
  echo "same filesystem"
else
  echo "different filesystem"
fi

      

+1


source







All Articles