Shell – From filename get mountpoint, device, LV, VG, PV names

block-devicefilesystemslvmmountshell

Given a relative pathname, how do I get its:

  • Mountpoint
  • Device
  • LVM LV name
  • LVM VG name
  • LVM PV name(s)

Best Answer

Summary

Given a relative $pathname, the following commands will set the following variables:

$absolute $mount $dev $lv $vg $pvs

Absolute pathname

absolute=$(readlink -f "$pathname")

Mountpoint and device

read -r dev mount <<< $(df --portability "$pathname" | awk 'NR==2{print $1 " " $6}')

Note: btrfs and zfs filesystems may span multiple devices, but only one will be listed here.

LV and VG names

read -r lv vg <<< $(sudo lvs -o lv_name,vg_name --noheadings  "$dev")

There is no need to worry about possible whitspaces in names as man lvm(8) says:

The valid characters for VG and LV names are: a-z A-Z 0-9 + _ . -

PV devices

pvs=$(sudo vgs -o pv_name --noheadings "$vg")

There may be more than one PV hosting your VG.

To deal with the edge case of special characters in device names, look into parsing pvs --reportformat json.

Bonus: Loop device backing file

backing=$(losetup -lnO BACK-FILE "$dev")
Related Question