Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if two files are on the same volume 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 a given file is on the boot volume?

I've tried using ln and checking to see if it fails, but sometimes ln fails for reasons other than the cross-device link error.

I also tried using a function that prints the path of a file and then checking to see if that path contains /Volumes/ as a prefix, but not all of my remote volumes get mounted to /Volumes/.

Is there another way?

like image 350
m81 Avatar asked Oct 19 '25 12:10

m81


2 Answers

You are asking if two files are on the same filesystem. The canonical way of checking this is to call the stat() system call on the two files and check if they have the same st_dev value, where st_dev identifies the device on which the file resides.

You can use the stat command in bash to perform 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 under OS X; the same check can be performed on Linux, but the stat command requires -c or --format instead of -f.

like image 123
larsks Avatar answered Oct 21 '25 01:10

larsks


With 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
like image 22
Cyrus Avatar answered Oct 21 '25 00:10

Cyrus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!