How To Format A Usb In Linux

How To Format A Usb In Linux

Reading time1 min
#Linux#USB#Storage#USBFormatting#CommandLine#FileSystem

Mastering USB Formatting in Linux: Precision Control for Portable Storage

Formatting a USB drive in Linux goes far beyond graphical interfaces. Command-line utilities expose full control over partitioning and filesystem selection—essential when performance, compatibility, or data integrity are non-negotiable.

Take, for example, a scenario encountered in field deployments: a firmware update fails mid-way because the update image exceeds FAT32’s file size limit, or an engineer accidentally wipes /dev/sda instead of a USB stick. Avoiding these headaches requires a precise, repeatable workflow.


1. Identify the Correct Device — No Second Chances

A single misstep here can result in catastrophic data loss. Always verify the device path with:

lsblk -p --output NAME,RM,SIZE,TYPE,MOUNTPOINT

Typical output:

NAME        RM  SIZE TYPE MOUNTPOINT
/dev/sda     0 477G disk 
├─/dev/sda1  0 512M part /boot/efi
├─/dev/sda2  0 476G part /
/dev/sdb     1  15G disk 
└─/dev/sdb1  1  15G part /media/$USER/USB

Rule of thumb: Only devices with RM=1 (removability flag) are likely to be USB sticks—but cross-check device size and unplug/replug if unsure. Labels may not always be up-to-date.


2. Unmount All Partitions Before Proceeding

Formatting or partitioning a mounted device can lead to filesystem corruption. Unmount all partitions:

sudo umount /dev/sdb1

If automounters are in play, check with mount | grep /dev/sdb.
Unmount every listed partition.


3. Erase Existing Partitioning: Clean Slate

Not strictly required, but eliminating residual partition tables (especially mixed GPT/MBR) prevents odd behavior.

Check for signatures:

sudo wipefs -a /dev/sdb

Or, for older systems:

sudo dd if=/dev/zero of=/dev/sdb bs=1M count=4 status=progress

Caveat: With dd, watch the block device identifier—one typo and the main disk is gone.


4. Partition Table: MBR vs. GPT?

  • MBR (msdos): Older BIOS compatibility, max 2TB.
  • GPT: Required for >2TB, UEFI systems, multiple partitions.

Create a new table:

sudo parted /dev/sdb --script mklabel gpt

Or for legacy systems:

sudo parted /dev/sdb --script mklabel msdos

Note: Some embedded devices require MBR to boot.


5. Define Partitions: Full-Disk, Single-Partition Approach

With parted:

sudo parted -a optimal /dev/sdb --script mkpart primary fat32 1MiB 100%
  • Avoid starting at 0 for alignment reasons—modern flash prefers 1MiB boundary.

Or interactively with fdisk:

  • n for new partition
  • Accept defaults
  • t then b for W95 FAT32
  • w to write changes

Validate changes:

lsblk -f /dev/sdb

6. Filesystem Selection: Tradeoffs

FilesystemMax File SizeOS SupportProsCons
FAT324GBAllUniversally readableCan't store images >4GB
exFAT>8PBWin/macOS/LinuxHandles large filesExFAT tools may be missing
NTFS16EBWin/LinuxJournalingSlower on flash
ext416TBLinuxJournaling, resilientNot natively supported by Win

For most interoperability, FAT32 or exFAT is preferred. For Linux backup disks, ext4 is typical.

Format examples:

# FAT32
sudo mkfs.vfat -F32 -n OPT_USB /dev/sdb1

# exFAT (Debian 12+, exfatprogs required)
sudo apt install -y exfatprogs
sudo mkfs.exfat -n XFER_USB /dev/sdb1

# EXT4
sudo mkfs.ext4 -L DATA_USB /dev/sdb1

# NTFS (if ntfs-3g is present)
sudo mkfs.ntfs -f -L WIN_DRV /dev/sdb1

Gotcha: mkfs.vfat on some distributions (>Debian 12) now requires dosfstools >= 4.2.


7. Eject: Always Flush Buffers

Data loss occurs when users yank drives immediately after a prompt. Confirm all IO is completed:

sudo umount /dev/sdb1
sync
sudo eject /dev/sdb

For stubborn mounts (target is busy), check with lsof | grep /dev/sdb1—background processes often hold references.


Automation Example: Scripted Formatting with Guardrails

Quick utility to create a FAT32 stick—prompting for confirmation, and detecting active mounts:

#!/bin/bash
set -e

DEV="$1"
if [[ -z "$DEV" || ! -b "$DEV" ]]; then
  echo "Usage: sudo $0 /dev/sdX"
  exit 1
fi

if mount | grep "$DEV"; then
  echo "Error: $DEV is mounted; please unmount and retry."
  exit 2
fi

echo "WARNING: $DEV will be reformatted and all data lost."
read -p "Type YES to proceed: " response
[[ "$response" == "YES" ]] || exit 3

sudo wipefs -a "$DEV"
sudo parted "$DEV" --script mklabel msdos mkpart primary fat32 1MiB 100%
sleep 1
sudo mkfs.vfat -F32 -n AUTOFMT "$DEV"1
sync
echo "Formatting complete. Remove device after LED activity stops."

Known issue: Some USB controllers cache writes even after sync; always visually check LED activity if present.


Non-Obvious Detail: File System Labels for Automation

For automated backup scripts or udev rules, set a unique filesystem label during formatting:

sudo mkfs.vfat -F32 -n BACKUP_2024 /dev/sdb1

Query label later with:

lsblk -o NAME,LABEL

This allows mounting by label (/dev/disk/by-label/BACKUP_2024), avoiding unstable device names across reboots.


Side Note: Alternatives Exist

Tools like gnome-disks (or KDE Partition Manager) provide convenience but often lack transparency in error handling. When precision matters or errors occur—fallback to the shell.


Wrap-Up

Formatting USB drives via the Linux CLI is rarely glamorous but always foundational. Habitually double-check device identifiers, align partitions, and select filesystems for your use case—resisting shortcuts prevents the classic “oops, wrong disk” scenario. No process is flawless, but with discipline and the steps above, failures become rare and recovery swift.