Bash: Find the disk a certain partition is on and put result into a variable

752 views Asked by At

What are some (reliable) tests to find the disk a certain partition is on and put that result into a variable?

For example, output of lsblk:

...
sda           8:0    0   9.1T  0 disk
└─sda1        8:1    0   9.1T  0 part /foopath
...
mmcblk0     179:0    0  29.7G  0 disk
├─mmcblk0p1 179:1    0   256M  0 part /barpath
└─mmcblk0p2 179:2    0  29.5G  0 part /foobarpath

If partition="/dev/mmcblk0p2", how can I put mmcblk0 as the disk it is a part of into a variable? Or similarly, if partition="/dev/sda1", how to put sda as the disk it is a part of into a variable?

disk=${partition::-1} seemed to be a hack until I encountered partitions such as mmcblk0p1, hence the request for a more reliable test...

The purpose of isolating the disk and using variable is to pass it to smartctl -n standby /dev/sda to find if disk is currently spinning, etc.

Operating environment is Linux Mint 19.3 and Ubuntu 20.

Any ideas?

1

There are 1 answers

0
algalg On BEST ANSWER

Thanks to @KamilCuk and @don_crissti ;)

"Print just the parent device" using lsblk

#!/bin/bash
partition="/dev/sda1"
disk="$(lsblk -no pkname "${partition}")"