Situation: Writing automated file mounting using Python on Linux. No Pythonic way that I can find to do it so using system calls (which technically means I am doing bash scripting, just that I am doing it through Python).

Problem: Getting disk labels are not sufficient for mounting the disks. For example, I am able to get the disk label /dev/sda, but only /dev/sda1 is mountable, /dev/sda2 being a SWAP partition.

fdisk outputs and parted outputs are not really helping in helping me decide which disks can be mounted (i.e. have a valid readable filesystem)

Question: How can I, by using Linux/Bash commands, find out which disks can be mounted (I don't mind chaining more than 10 grep pipes to get my final result).


Both lsblk and blkid can be used to find out what's in a partition (e.g. swap, known filesystem, raw data). They both have various options to specify the output format so you can extract just the info you need (e.g. filesystem type, fs label, uuid, etc).

IMO blkid is a better tool for scripted operations and, in my experience, is better at detecting what an existing partition is being used for, no matter what kind of block device is being examined (e.g. lsblk doesn't know what to do with a ZFS zvol. blkid treats it just like any other block device - which is exactly what it should do because that's exactly what a ZVOL is). lsblk can be used in scripts, but is, IMO, oriented more towards interactive use with pretty-printed output.

e.g. on one of my systems:

# blkid /dev/sda*
/dev/sda: PTUUID="3a1e16ae" PTTYPE="dos"
/dev/sda1: UUID="08799b67-8ed7-4cee-aea1-0f9e7bd1fc04" TYPE="ext4" PARTUUID="3a1e16ae-01"
/dev/sda2: UUID="db8bda5f-4f18-4abb-a151-08494e398047" TYPE="swap" PARTUUID="3a1e16ae-02"
/dev/sda3: UUID="fc967791-b9cf-4145-9047-8a8b223ac4bb" TYPE="xfs" PARTUUID="3a1e16ae-03"

Or if I want just the filesystem type of /dev/sda1:

# blkid -o value --match-tag TYPE /dev/sda1

See the man page for blkid for details.

BTW, file -s can also be used but the output is harder to parse. e.g.

# file -s /dev/sda1
/dev/sda1: Linux rev 1.0 ext4 filesystem data, UUID=08799b67-8ed7-4cee-aea1-0f9e7bd1fc04 (needs journal recovery) (extents) (large files) (huge files)

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.