2

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?

nooblag
  • 678
  • 3
  • 23
  • So extract part of the string between the last `/` and the first digit? – KamilCuk Oct 01 '20 at 11:54
  • 1
    I believe the OP wants the strings extracted as per the disk names, like: `mmcblk0` and `sda`... – User123 Oct 01 '20 at 11:56
  • Yeah, I'm not sure if pattern matching is the way to go since it seems the disk names can vary structure? I'm not certain of that though. Finding the "root" name of the drive is what I'm after (like in `lsblk` output above). Hope that helps clear it up! – nooblag Oct 01 '20 at 12:00
  • `is to pass it to smartctl` just pass `/dev/sda1`, it will pick the disc by itself. @edit ok, so seems to depend on the disc, works for my partitions as far as I could tell. – KamilCuk Oct 01 '20 at 12:01
  • Nah that doesn't work for me for partitions. `smartctl` seems to want the disk. i.e. `smartctl -n standby /dev/sda` returns `Device is in IDLE_A mode` but .../sda1 doesn't. – nooblag Oct 01 '20 at 12:03
  • 1
    Here is the answer: https://unix.stackexchange.com/questions/226420/how-to-get-disk-name-that-contains-a-specific-partition – KamilCuk Oct 01 '20 at 12:29

1 Answers1

0

Thanks to @KamilCuk and @don_crissti ;)

"Print just the parent device" using lsblk

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