Reputation: 642
The stat
system call (man 2 stat
) returns the ID of the device containing the file.
In a script, this ID can be obtained with, say
perl -e 'print((stat "/tmp/blah.txt")[0])'
Given the ID, how do I obtain the name of the disk, such as /dev/sda2
or /dev/disk1s1
?
I want to do it in a script (bash, perl, etc.) preferably in a portable way so that it works reliably both on MacOS and Linux.
Upvotes: 2
Views: 1007
Reputation: 50805
I think you're trying to re-invent the wheel.
Given a file name, the filesystem name it belongs to can be found in last row's first column in df
's output. E.g:
df -P /tmp | awk 'END { print $1 }'
Upvotes: 1
Reputation: 14491
You can use 'df' to enumerate the file system, and create a map between device IDs and disk. Recall the each df line will list the mount point (/dev/sda1, ...) in the first column, and the mount point on the 5th column).
The following script uses bash associative array for the map, and stat -c '%d' to extract the 'dev' value of a given path.
# Create map dev2fs
function file2dev {
stat -c '%d' "$1"
# If needed, use Perl equivalent
# perl -e 'print ((stat($ARGV[0]))[0])' "$1"
}
declare -A dev2fs
while read fs size used available use mount ; do
id=$(file2dev $mount);
[ "$id" ] && dev2fs[$id]=$fs
done <<< "$(df)"
# Map a file to device
dev=$(file2dev /path/to/file );
echo "Device=${dev2fs[$dev]}"
Also, possible to iterate over mounted file system using 'mount -l'. I'm not sure which one exists on MacOS.
Upvotes: 1