Thursday, 19 January 2023

Formatting USB Flash Drive on Linux

 

Under UNIX-like operating systems, formatting a USB flash drive, in fact even a hard drive, requires knowing the file name for the partition that is to be formatted. These are files under the /dev directory, like for example, /dev/sdb1. So the interesting question to be asked is how does one come to know of the file representing the partition on the device? Immediately after connecting a USB flash drive to my laptop running Arch Linux and looking at the last few lines of ‘dmesg’ output gives:

sd 4:0:0:0: [sdb] 31703040 512-byte logical blocks: (16.2 GB/15.1 GiB)
Notice the ‘sdb’ within square brackets. This hints that the device file would start with /dev/sdb. Further, running:
$ ls -l /dev/sdb*
brw-rw---- 1 root disk 8, 16 Jan 31 23:55 /dev/sdb
brw-rw---- 1 root disk 8, 17 Jan 31 23:49 /dev/sdb1
And keeping it mind that it is a partition that is formatted, confirms the file that we are searching to be /dev/sdb1. Now, for formatting, if it is the EXT4 filesystem that is to be built then run:
mkfs.ext4 -L <label> /dev/sdb1
Use of the  -L <label> switch is optional. It gives a fancy name to the device that is often visible when automounting in a desktop environment like KDE or GNOME. After the above commands successful termination, one might want to print the partition table on the device for assurance:
# parted /dev/sdb print
Model: JetFlash Transcend 16GB (scsi)
Disk /dev/sdb: 16.2GB
Sector size (logical/physical): 512B/512B
Partition Table: msdos

Number  Start   End     Size    Type     File system  Flags
1      16.4kB  16.2GB  16.2GB  primary  ext4         boot, lba
Notice that in the above case, the complete device (/dev/sdb) was given to parted and not just one partition. Manual mounting can be as simple as:
mount -t ext4 /dev/sdb1 <dir>

No comments:

Post a Comment