Using the mkfs Command in Linux for Formatting a Filesystem on a Disk or Partition

Popular:
LEVEL UP YOUR SERVER SETUP! APPLY AVA AND LAUNCH WITH A 15% DISCOUNT
USE PROMO:

The mkfs (Make Filesystem) command in Linux is used to create a new filesystem on a disk partition or storage device. Formatting a partition correctly is essential for efficient data storage and system performance. This guide explains how to use the mkfs command to format a filesystem on a disk or partition in Linux.

Step 1: Identify the Disk or Partition

Before formatting a partition, identify the correct disk device name using:

lsblk

or

sudo fdisk -l

Example output:

sda 8:0 0 500G 0 disk ├─sda1 8:1 0 100G 0 part / ├─sda2 8:2 0 400G 0 part /mnt/data

Here, /dev/sda2 is an available partition for formatting.

Step 2: Unmount the Partition (If Mounted)

Before formatting, unmount the partition to prevent conflicts:

sudo umount /dev/sda2

**Step 3: Format the Partition Using **mkfs

sudo mkfs.ext4 /dev/sda2
sudo mkfs.xfs /dev/sda2

3. Format as FAT32 (For Cross-Platform Compatibility)

sudo mkfs.vfat -F32 /dev/sda2

4. Format as NTFS (For Windows Compatibility)

sudo mkfs.ntfs /dev/sda2

Step 4: Label the Filesystem (Optional)

To add a label to the newly formatted partition:

sudo e2label /dev/sda2 DataPartition # For EXT4 sudo xfs_admin -L DataPartition /dev/sda2 # For XFS

Step 5: Mount the New Filesystem

Create a mount point:

sudo mkdir -p /mnt/data

Mount the partition:

sudo mount /dev/sda2 /mnt/data

Verify the mount:

df -h

Step 6: Add to /etc/fstab for Automatic Mounting

To mount the partition automatically at boot, add it to /etc/fstab:

echo '/dev/sda2 /mnt/data ext4 defaults 0 2' | sudo tee -a /etc/fstab

Replace ext4 with the appropriate filesystem type if different.

Conclusion

The mkfs command is a powerful tool for formatting partitions and preparing storage devices in Linux. By following these steps, you can efficiently format, label, and mount a partition for use.