How to Find Filesystem of an Unmounted Partition from a Script

block-devicecommand linefilesystemssystem-installation

I'm writing a custom automated install using AIF (Arch Installation Framework), and I need to find the filesystem on a partition given a partition.

So far I have this:

grok_partitions () {
    local partitions=
    for label in `ls /dev/disk/by-label | grep "Arch"`
    do
        if [ $label == "Arch" ]
        then
            mount_point="/"
        else
            IFS="-" read base mount <<< "${label}"
            mount_point="/${mount}"
        fi

        local partition=$(readlink -f /dev/disk/by-label/${label})
        local part_no=$(echo ${partition} | grep -Po '\d+')
        local fs=$(parted -mls | grep "^${part_no}" | cut -d: -f5)
        partitions+="${partition} raw ${label} ${fs};yes;${mount_point};target;no_opts;${label};no_params\n"
    done

    # do the swap
    if [ -e /dev/disk/by-label/swap ]
    then
        local partition=$(readlink -f /dev/disk/by-label/swap)
        partitions+="$partition raw swap swap;yes;no_mountpoint;target;no_opts;swap;no_params"
    else
        # if there's no labeled swap, use the first one we find
        local partition=$(fdisk -l | grep -m1 swap | awk '{ print $1 }')
        if [ ! -e $partition ]
        then
            echo "No swap detected. Giving up."
            exit 1
        fi
        partitions+="$partition raw no_label swap;yes;no_mountpoint;target;no_opts;no_label;no_params"
    fi

    echo -n ${partitions}
}

This worked fine on my machine with only one hard drive, but it failed (obviously) when running in my VM running on a LiveCD (the LiveCD was being picked up as another drive, /dev/sr0).

I've thought of a couple of hacks I could try:

  • mount $partition; grep $partition /etc/mtab | awk ...
  • use parted -mls, but pull out the partition I care about with clever scripting, then parse as I already do in the scriptt

Is there a better, simpler way of doing this? I already have the partitions I'm interested in, and I only need to find their filesystems (as well as find available swap).

Best Answer

I think I found the answer: blkid

From the man page:

The blkid program is the command-line interface to working with the libblkid(3) library. It can determine the type of content (e.g. filesystem or swap) that a block device holds, and also attributes (tokens, NAME=value pairs) from the content metadata (e.g. LABEL or UUID fields).

Apparently it prints the device name along with the filesystem type (along with some other useful information). To get a list of all devices with their types:

blkid | sed 's!\(.*\):.*TYPE="\(.*\)".*!\1: \2!'

To find all /dev/sd*/ devices, just add in a grep:

blkid | grep "/dev/sd.*" | sed 's!\(.*\):.*TYPE="\(.*\)".*!\1: \2!'

Then just cut or awk to get what you need.

Related Question