Shell Script to Create and Format a Partition

Last updated: December 20, 2023 | Bobbin Zachariah

Do you have a new disk on your Linux system and want to format it? Here we have created a bash script that creates and formats a partition with the ext4 filesystem.

Prerequisites:

  • Require a disk with no filesystem and no partition.
  • Need root or sudo privilege to run the script.

Bash Script to Create and Format Partition

This bash script simplifies the process of creating and formatting a disk partition on a Linux system.

It provides the following functionalities:

# 1. Checks and displays the status of existing disks (using lsblk).

# 2. Creates a new partition on a selected disk (using parted command).

# 3. Formats the newly created partition with the ext4 filesystem.

Output:

$ sudo ./partition_format_disk.sh
/dev/sda is formatted with ext4 filesystem and mounted to / with 1 partition.
/dev/sdb is formatted with swap filesystem and mounted to [SWAP] with 1 partition.
/dev/sdc is no filesystem with 0 partition.
Enter the disk identifier with no filesystem and no partition (e.g., /dev/sdX): /dev/sdc
Created /dev/sdc with 1 partition. Disk partition completed.
Format /dev/sdc with ext4 (confirm yes/no): yes
Partition /dev/sdc creation and formatting with ext4 complete.

Script

#!/bin/bash

num_of_partitions() {
        echo $(lsblk -n -o NAME "$1" | tr -dc '[:alnum:]\n\r' | wc -l)
}

# Function to display current mount points and filesystem types
display_mount_info() {
        # Get a list of all available disks
        disks=$(lsblk -no NAME,TYPE,FSTYPE,MOUNTPOINTS | grep -vE '^Filesystem|tmpfs|cdrom|loop|udev' | grep disk | sed 's/  */,/g')

        for _disk in $disks; do
                disk_name=`echo $_disk | awk -F"," '{print $1}'`
                dtype=`echo $_disk | awk -F"," '{print $2}'`
                mountp=`echo $_disk | awk -F"," '{print $4}'`
                disk_type=`echo $_disk | awk -F"," '{print $3}'`

                # Display number of partitions associated with the disk
                num_partitions=$( num_of_partitions "/dev/${disk_name}" )

                disk_msg="/dev/${disk_name} "
                if [ "${disk_type}" != "" ] ; then disk_msg="${disk_msg} is formatted with ${disk_type} filesystem "; else disk_msg="${disk_msg} is no filesystem "; fi
                if [ "${mountp}" != "" ] ; then disk_msg="${disk_msg} and mounted to ${mountp}"; fi
                if [[ "${num_partitions}" != 0 && "${disk_type}" != "" ]] ; then
                        disk_msg="${disk_msg} with ${num_partitions} partition."
                else
                        if [[ "${num_partitions}" != 0 ]] ; then
                                disk_msg="${disk_msg} with `expr ${num_partitions} - 1` partition."
                        else
                                disk_msg="${disk_msg}, no partition."
                        fi
                fi

                echo ${disk_msg}
        done
}

# Function to check if a disk has no filesystem or partition
check_empty_disk() {
        local disk=$1
        if [[ ! -e "$disk" || -n $(lsblk -no FSTYPE "$disk") ]]; then
                echo "Invalid disk. Please provide a valid disk identifier with no filesystem or partition."
                exit 1
        fi
}

# Check for superuser privileges
if [ "$EUID" -ne 0 ]; then
        echo "Please run this script as root or using sudo."
        exit 1
fi

# Display current mount points and filesystem types
display_mount_info

# Prompt user for disk selection
read -p "Enter the disk identifier with no filesystem and no partition (e.g., /dev/sdX): " disk

# Verify the selected disk
check_empty_disk "$disk"

num_partitions=$( num_of_partitions "${disk}" )

if [ `expr $num_partitions - 1` == 0 ] ; then
        # Create a new primary partition using all available space
        parted -a optimal -s "$disk" mklabel msdos mkpart primary ext4 0% 100%
        if [ "$?" != "0" ] ; then echo "Failed to create partition for ${disk}."; exit 1; fi
        echo "Created ${disk} with 1 partition. Disk partition completed."
fi

read -p "Format ${disk} with ext4 (confirm yes/no): " answer
if [ "${answer}" == "yes" ] ; then
        # Format the partition with ext4
        mkfs.ext4 -F "${disk}" &>/dev/null
        if [ "$?" != "0" ] ; then echo "Failed to format partition with ext4 ${disk}"; exit 1; fi

        echo "Partition ${disk} creation and formatting with ext4 complete."
fi

In the script

The “display_mount_info” function retrieves information about available disks, their types, mount points, and associated filesystems. 

The following command in the script will list all available disks in the system and will format the output of lsblk with the required information i.e. NAME (Disk Name), Type (disk or partition), FSTYPE (types of partition) and MOUNTPOINT (where exactly that drive is mounted) and finally replacing multiple spaces with “,” using the “sed” command.

disks=$(lsblk -no NAME,TYPE,FSTYPE,MOUNTPOINTS | grep -vE '^Filesystem|tmpfs|cdrom|loop|udev' | grep disk | sed 's/  */,/g')

To create a partition on the disk, we need a disk with no file system or partition, the following command helps to check that if we found FSTYPE for a given disk and will print a message and exit from script and it is taken care of by “check_empty_disk” function.

 if [[ ! -e "$disk" || -n $(lsblk -no FSTYPE "$disk") ]]; then
   	echo "Invalid disk. Please provide a valid disk identifier with no filesystem or partition."
    	exit 1
  fi

Finally, everything is verified by the script will execute the parted command that does magic to create a partition for the given disk.

parted -a optimal -s "$disk" mklabel msdos mkpart primary ext4 0% 100%

It creates a partition with a label as msdos, primary partition with ext4 file system and will use the whole drive to create the partition.

SHARE

Comments

Please add comments below to provide the author your ideas, appreciation and feedback.

Leave a Reply

Leave a Comment