If I have a file
/abc/def/ghi/jkl, is there a way to tell which device it is located on, or should I parse
/etc/mtab and see what matches
df will tell you device name and mount point, and ls will tell you device numbering:
paul $ pwd /home/paul/SandBox/Toys/hSort paul $ ls -l ReadMe -rw-r--r-- 1 paul paul 296 Jan 8 2020 ReadMe paul $ df ReadMe Filesystem 1K-blocks Used Available Use% Mounted on /dev/sda9 103818480 3796556 94725184 4% /home paul $ ls -l /dev/sda9 brw-rw---- 1 root disk 8, 9 Jul 12 12:10 /dev/sda9
If on Linux, you can run
findmnt (manpage) on the path of the file:
findmnt -T /abc/def/ghi/jkl
Since the output is not meant to be parsable, if you want to read the result of a column (in this case SOURCE) into a variable you could do:
source=$(findmnt -rno SOURCE -T /abc/def/ghi/jkl)
$source may not always be the path to a block device file like in the cases of network or fuse file systems, tmpfs, etc.).
There are several, but it depends on what tools you can use. Are you on a shell, are you writing a script or program? In what language?
stat() function will return a device identifier for the file specified.
So will the
stat(1) command. You could maybe use
stat -c %D filename in a script. For example:
stat -c %D /mnt/persistent/test
will give, "0821". That means device 8, minor 33 ("21" is 33 in hex). So I can look into
/dev what device has numbers 8, 33:
ls -l /dev | grep " 8, *33 " brw-rw---- 1 root disk 8, 33 Jun 28 19:08 sdc1
Otherwise, yes, use
realpath and match with mtab. In the same example:
REALPATH="$( realpath /mnt/persistent/test )" df | grep ^/ | tr -s " " \ | while read row; do PREFIX=$( echo "$row" | cut -f 6 -d " " ) if ( echo "$REALPATH" | grep ^$PREFIX > /dev/null ); then echo "$row" | cut -f 1 -d " " fi done | sort | tail -n 1
Although, as @Freddy pointed out, this whole script comes in a very poor second after
df's own syntax:
df --output=source /mnt/persistent/test | tail -n1
stat is your friend here. The "device" field will tell you what device your file is on. Read this for more info on how to interpret the device field.