2

I need to generate a string for another application to locate my file. I need to know how to access this file dynamically.

customfile=/dev/sda1:/images/myfs.squashfs

Let's say I can stat some/file/here.txt. What command do I use to determine it's block device, and it's absolute path from that device?

Also, how do I then determine the absolute path to here.txt from the device?

1
  • You can get the device associated with the file with "df --output=source <pathtofile> | tail -1". If logical volumes are involved, more steps may be required. Commented Sep 27, 2017 at 9:22

1 Answer 1

3

You can find on which device your file is with df. Select the output columns with --output option. Note that df outputs the device which contains the filesystem. If you use LVM, LUKS, mdraid etc, the source column will contain the path of the logical device.

df --output=source $path |tail -1

From target column you can get the mount point of the device:

df --output=target $path |tail -1

To get path relative to the root of the mounted device, remove the mount point from the beginning of the path. Using shell parameter expansion:

echo ${path#$(df $path --output=target |tail -1)}
5
  • Perfect. Now, how about it's absolute path on that device? Commented Sep 27, 2017 at 9:24
  • 1
    Added an example using shell parameter expansion. Commented Sep 27, 2017 at 9:33
  • Greatly appreciated! Commented Sep 27, 2017 at 9:36
  • Running these 3 commands with /boot/vmlinuz-linux gives me /dev/sda1, /boot, and /vmlinuz-linux. Perfect. Commented Sep 27, 2017 at 9:41
  • You should also post this answer over on the linked [duplicate] question as well, as this is far simpler and better answer. Commented Aug 2, 2023 at 0:11

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.