1

Given a block device (e.g, /dev/sda), how to determine the names of its partitions (if any) in a script (i.e. without user interaction)?

1

lsblk prints out all related block devices. This includes the partitions of said device. Since it of course includes the device itself and lsblk does not allow for excluding specific devices the example solution below simply uses inverted grep:

lsblk -o KNAME -n /dev/mmcblk0 | grep -v "^mmcblk0$"

For full paths (which also simplifies the generation of the grep string) one can use -p, e.g.:

lsblk -po KNAME -n /dev/mmcblk0 | grep -v "^/dev/mmcblk0$"
0

There are a couple of tools which you can use for this. One of the tools which I tend to use a lot is fdisk. fdisk is something which will list the partitions of your block device and also state the exact sizes for you. fdisk is quite a versatile program which can also modify the internal properties of your partitions in terms of storage so be very careful using it.

In the case of listing a partition you simply want to execute the following command: fdisk -l <name of block device>. From this point you're then able to see the exact sizes, name and type of the partitions you seek. If you would like to use fdisk further for other uses relating to the hard disk then use the man command to open the manual page for fdisk:

man fdisk

2
  • I phrased my question not carefully enough and have edited it now. I meant automatically within a script and without any user interaction. There are lots of way for finding this out interactively in Linux. – stefanct Feb 19 '19 at 11:42
  • In this case you should consult the bash programming language. You will be able to use Linux commands in a programmable environment and you won't require any further user interaction. I understand what you're asking now. Please feel free to write your script and message me if you would like a hand or just general feedback – A.Hussain Feb 19 '19 at 12:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.