The Linux Newbie Guide  ⇒    Fundamentals     Advanced     Supplement   Command Index   ENG⇒中
All rights reserved, please indicate the source when citing
 

Disk Proficiency in Linux

1.0 Hard Disk and File System Directory Structure in Linux
       Linux Filesystem
           ext2 File Systemext2 File System
           ext3/ext4 File System
       Unix Directory Structure
       Hard Disks and Device Files in Linux
1.1 Displaying Hard Disk Information
       df : Display disk usage
       du : Display directory usage
       blkid : Display disk information
1.2 Disk Partitioning
       Traditional MBR Disk Partitioning
           Primary Partition
           Extended Partition
                Logical Partition
           Using fdisk to partition disks
       Modern GPT Disk Partitioning
           Using parted to partition disks
       partprobe : Reload Partition Table
1.3 Formatting File Systems
       mkfs : Format the filesystem
       tune2fs : Adjust ext filesystem settings
       e2label : Set the label of a filesystem
       fsck : Check and attempt to repair the filesystem
1.4 Mounting Filesystems
       Basic usage of mount
         /etc/mtab : File containing the currently mounted filesystems
       Mounting by Label
       Mounting by UUID/PARTUUID
       Mounting USB Flash Drives
       Mounting a CD-ROM
       Configuring Automatic Mounting at Boot using /etc/fstab
       umount : Unmounting filesystems
       Mounting Virtual Device

ENG⇒中ENG⇒中
  

Linux Hard Disk Basics


1.0 Hard Disk and File System Directory Structure in Linux


Linux Filesystem
When we read and write a file, we don't need to worry about which sector, track, or cylinder the file is stored on the hard disk. We also don't need to worry about the type of storage media, such as hard disk/USB flash drive/CD-ROM, because the file system handles it for us.

The file system manages how storage media is organized, so different operating systems support different file systems. Each file system has its own advantages and disadvantages. For example, when formatting a USB flash drive in Windows 7/Windows 10, options may include FAT, FAT32, NTFS, exFAT, and others.

format option

If an SD card is formatted with Windows' native "NTFS" file system, some digital cameras or phones may not be able to read it. Formatting it as "FAT" limits single file size to 2GB, while "FAT32" allows files up to 4GB. Filesystems affect the handling capabilities of files, such as copying files from a Linux filesystem to a USB flash drive (usually formatted with FAT32), which may result in the loss of permissions and other information.

Windows can only be installed on the NTFS file system, leaving no other choices, but Linux offers more flexibility and can be installed on native ext2/ext3/ext4 or other contributed file systems like ReiserFS/xfs/Btrfs, among others. Some file systems are better suited for handling large files, while others are more efficient with small files or specifically designed for databases, giving users more choices and, at the same time, more decisions to make.

The file system is an essential element of a PC's operating system. For example, Microsoft's early operating systems mainly provided file system support and were named "Disk Operating System" (DOS). Linux's native file system is ext2 or ext3/ext4.

^ back on top ^

Unix Directory Structure
Before explaining the Unix/Linux directory structure, let's compare it with the more familiar Windows. In Windows, when we enter "START C:" in command mode, it opens the Windows File Explorer, and we may see directories like:
windows c driver

Due to the conditioning from using Windows, I initially had trouble finding "C drive" or "C:" when I started using Linux. The concept of a "local disk (C:)" doesn't exist in Unix/Linux. Instead, Unix/Linux has a "Filesystem Directory Structure" or "Filesystem Hierarchy Standard" (FHS), as shown in the image below:

linux Filesystem Hierarchy Standard
The Linux FHS can consist of one or multiple hard disks, and it starts at the top-level directory, which is the root directory "/". The directories under the root directory are as follows (colored differently in the image for distinction):

The Linux FHS can consist of one or multiple hard disks, and it starts at the top-level directory, which is the root directory "/". The directories under the root directory are as follows (colored differently in the image for distinction):

Regardless of the Linux distribution, the file system directory structure is generally the same because most distributions follow the "Filesystem Hierarchy Standard" (FHS). The content of FHS can be summarized as follows:

^ back on top ^

Hard Disks and Device Files in Linux
In Linux, device files are special files that represent various devices in the system. They allow user-level programs to interact with hardware devices without needing to know low-level details. Here are some common Linux device files and their brief explanations:

These are just a few examples of device files in Linux. The /dev directory contains many other device files, each representing a different hardware device or interface in the system.

In the above table, the focus is on item 1 "/dev/sda, /dev/sdb, ..." which represents block device files in Linux. These device files are crucial for later operation examples as they allow interaction with physical storage devices such as hard drives and USB drives. When performing tasks like formatting, partitioning, or managing storage devices in Linux, it is essential to work with the appropriate device file, such as "/dev/sda" or "/dev/sdb." Caution should be exercised while using these device files, as any actions performed on them directly affect the data on the associated storage devices. Always verify the device you are working with to avoid unintended consequences.



^ back on top ^

1.1 Displaying Hard Disk Information
df : Display disk usage
The most straightforward way to understand disk usage in Linux is by using the df command (disk free). df displays the usage of each mounted partition. Example:
$  df
Filesystem           1K-blocks      Used Available Use% Mounted on
/dev/sda5             13172924   3837376   8655600  31% /
/dev/sda2              4956316    154760   4545724   4% /home
/dev/sda1               194442     12060    172343   7% /boot
tmpfs                   514304        12    514292   1% /dev/shm
/dev/sdb1             31210416     88736  31121680   1% /media/disk

In the above example, the "Filesystem" column shows two devices, "/dev/sda#" (# being a number) and "/dev/sdb#", indicating the presence of two hard drives. For instance, "dev/sda" has four partitions: "/dev/sda5", "/dev/sda2", and "/dev/sda1", mounted at "/", "/home", and "/boot", respectively.

The "tmpfs" ("/dev/shm") is not a physical disk but rather a type of RAM Disk. It is like a virtual disk in memory and is present in most Linux distributions by default. Data stored in "/dev/shm" operates at RAM speed, making it useful for temporary file operations. However, remember that data in "/dev/shm" is volatile and will be lost upon reboot.

The main options are:

To check the location of a specific file, append the file path to df:

Example:
$ df -T ←Displays the filesystem type of each partition Filesystem
Filesystem    Type   1K-blocks      Used Available Use% Mounted on
/dev/sda5     ext3    13172924   3876612   8616364  32% /
/dev/sda2     ext3     4956316    154656   4545828   4% /home
/dev/sda1     ext3      194442     12060    172343   7% /boot
tmpfs        tmpfs      514304        12    514292   1% /dev/shm
/dev/sdb1     ext2    20635700     44992  19542472   1% /media/DB
/dev/sdc1     vfat    31195120        16  31195104   1% /media/disk
$ df -t ext3 -t vfat ←Displays only "ext2" and "vfat"
Filesystem    Type   1K-blocks      Used Available Use% Mounted on
/dev/sdb1     ext2    20635700     44992  19542472   1% /media/DB
/dev/sdc1     vfat    31195120        16  31195104   1% /media/disk

When df is followed by a directory or file, it shows the partition on which that file is located.

Example:
$ df -h /bin/bash ←Check the location of the file "/bin/bash" Filesystem Size Used Avail Use% Mounted on
Filesystem            Size  Used Avail Use% Mounted on
/dev/sda5             3.9G  3.6G  173M  96% /

^ back on top ^

du : Display directory usage
du (disk usage) displays the usage of directories and is similar to the tree command, but it also shows the size of directories.

Example:
$ du /etc ←Displays the size of subdirectories under the directory "/etc"
40      /etc/redhat-lsb
8       /etc/yum/pluginconf.d
24      /etc/yum
du: `/etc/audisp': Permission denied
32      /etc/samba
8       /etc/sysconfig/modules
388     /etc/sysconfig/network-scripts
... (continued)
$ du /etc | sort -n ←Sort by directory size

By default, the sizes are displayed in 1024 bytes. The option du -h is used to display sizes in KB, MB, or GB.

Other commonly used options include: Example:
$ du -sh ~/←Displays the total size of the home directory 16M /home/aaa/
16M      /home/aaa/

If you are logged in with a regular user account, some directories or files may not be accessible due to permission issues, which could affect the statistics. Most disk-related commands, except for du and df require superuser (root) privileges to operate.

For more explanations of du operations, please refer to the provided link .

^ back on top ^

blkid : Display disk information
In Unix/Linux, hard drives and other storage media are referred to as "block devices." Therefore, the blkid tool is used to display block device IDs. (Typically, root privileges are required to execute and display the information correctly, and even filesystems that are not mounted will be shown.)

blkid is a useful tool to gather information about hard drives, and its usage is straightforward, as shown in the following example.

Example:
# blkid ←Displays disk information
/dev/sda5: LABEL="/" UUID="24328158-f8c3-4c5e-9be0-cbd1ceee581f" SEC_TYPE="ext2" TYPE="ext3"
/dev/sda1: LABEL="/boot" UUID="8ab1dede-36dd-4469-a174-ffb04f9ee6df" SEC_TYPE="ext2" TYPE="ext3"
... (continued)

The main information provided includes the device file, label name, UUID, and filesystem type. The UUID (Universally Unique Identifier) is a unique number generated during formatting, and it can be used for mounting, LVM, or RAID to identify the hard drive or partition. It remains constant even if the Linux kernel is upgraded, BIOS settings are changed, or a different Linux distribution is used.

To display specific information, you can use the "-s" option followed by [LABEL], [UUID], or [TYPE]. For example:

Example:
# blkid -s TYPE ←Displays the filesystem type for each partition
/dev/sda5: TYPE="ext3"
/dev/sda1: TYPE="ext3"
/dev/sda2: TYPE="ext3"
/dev/sda3: TYPE="swap"
/dev/sdb1: TYPE="ext3"
/dev/sdc1: TYPE="vfat"
# blkid -s LABEL ←Displays the label name for each filesystem (only if labeled)
/dev/sda5: LABEL="/"
/dev/sda1: LABEL="/boot"
/dev/sda2: LABEL="/home"
/dev/sda3: LABEL="SWAP-sda3"
/dev/sdb1: LABEL="data"
/dev/sdc1: LABEL="PEN_FLASH"
# blkid -s UUID ←Displays the UUID for each partition
/dev/sda1: UUID="9da5bd9a-300f-42f8-8d32-49af244a4c4f"
/dev/sda2: UUID="374b2969-3c63-438f-8762-3db53f96f409"
/dev/sda3: UUID="a2e9407d-8a07-4d68-8a4a-ebd712280f10"

To customize the output related to devices, you can use the "-o" option followed by [device], [full], or [value]. For example:

Example:
# blkid -o device ← Displays the device files for each device
/dev/sda5
/dev/sda1
/dev/sda2
/dev/sda3
/dev/sdb1
/dev/sdc1

^ back on top ^

1.2 Disk Partitioning
Disk partitioning is the process of dividing a large storage device, like a hard disk, into smaller sections or partitions. This concept is similar to dividing a large house into multiple rooms. By partitioning a hard disk, each partition functions as if it were a separate disk. For example, in Windows/DOS, one physical hard disk can be divided into partitions such as C:/D:/E:, making it appear as if there are multiple separate disks.

The benefits of partitioning a hard disk into multiple partitions include:

However, the main drawback of partitioning is that if the physical hard disk fails, all the partitions on that disk may become inaccessible. To mitigate this risk, one can consider distributing data across partitions on separate physical disks.

The concept of disk partitioning is not specific to any particular operating system. Different operating systems may have varied terminology and support different partitioning tables. Two commonly used partitioning tables are the traditional Master Boot Record (MBR) and the newer GUID Partition Table (GPT), both of which are well-supported by Linux.

After partitioning a disk, additional steps are required: This information was last updated on: Oct 23 2021
Currently, newer versions of operating systems such as Windows 10 and above, or motherboards that no longer support MBR (Master Boot Record), recommend using GPT (GUID Partition Table) for partitioning.

^ back on top ^

Traditional MBR Disk Partitioning
MBR (Master Boot Record) is the traditional way of disk partitioning and booting for PCs. It has been in use since PC-DOS 2.0 in 1983 and is still widely used today. One of its advantages is that it is supported by almost all PCs. However, MBR has limitations, as it only supports 32-bit LBA addressing, allowing for a maximum disk capacity of approximately 2.19TB (232 x 512 bytes) or less. This limitation was inconceivable at the time of its creation, as hard disks were not expected to exceed 2TB. The MBR method involves the BIOS reading the first 512 bytes of the disk, known as the "Master Boot Record," located at Cylinder 0, Head 0, Sector 1, when the PC boots.

Windows generally designates the primary partition on which the OS boots as the "C:" drive, and the other partitions are sequentially assigned drive letters such as "D:" and "E:". However, Linux does not follow the same naming convention for partitions.

Linux Naming Convention for Partitions:
For example, if a SATA hard disk is divided into 4 primary partitions, the device names for each partition would be as follows (highlighted in green):
SATA Hard Disk
SATA Hard Disk @port 1 /dev/sda1 /dev/sda2 /dev/sda3 /dev/sda4
SATA Hard Disk @port 2 /dev/sdb1 /dev/sdb2 /dev/sdb3 /dev/sdb4

Once again, it is emphasized that the number part of the Primary Partition must be less than or equal to 4.
For example, let's consider a SATA hard disk at port 1 that is partitioned into 2 Primary Partitions and 1 Extended Partition. The Extended Partition is further divided into 3 Logical Partitions. The device names for each partition would be as follows:

To create more than 4 partitions on a disk, an extended partition is used, and the device names would be as follows (highlighted in green):
Partitioning of the Hard Disk:2 Primary Partitions+3 Logical Partitions
Primary
Partition 1
Primary
Partition 2
Extended Logical
Partition 1
Logical
Partition 2
Logical
Partition 3
/dev/sda1 /dev/sda2 Extended /dev/sda5 /dev/sda6 /dev/sda7

The Extended Partition is used as a pointer and cannot be directly utilized. It needs to be further divided into Logical Partitions to be usable. The numbering for the Logical Partitions starts from 5 onwards.

As shown in the example below using the df command to display disk information, the partition named "/dev/sda5" (which corresponds to the root directory) is a logical partition.

Example:
$  df
Filesystem           1K-blocks      Used Available Use% Mounted on
/dev/sda5             13172924   3837376   8655600  31% / ←logical partition
/dev/sda2              4956316    154760   4545724   4% /home
/dev/sda1               194442     12060    172343   7% /boot
tmpfs                   514304        12    514292   1% /dev/shm
/dev/sdb1             31210416     88736  31121680   1% /media/disk

The extended partition cannot be directly used for data storage and must be further divided into logical partitions. Logical partitions are numbered starting from 5.

In summary, regardless of the number of partitions on a hard disk, only primary partitions can be set as the "Active Partition," which is the partition from which the system boots. Logical partitions cannot be set as the active partition.



^ back on top ^

Using fdisk to partition disks
Partitioning a hard drive using the traditional MBR method is done using the fdisk utility. Since fdisk is an interactive program, it is not complicated to operate and does not require memorizing commands. However, it is essential to understand the background knowledge of primary partitions, extended partitions, and logical partitions, as well as be familiar with the device files used for hard drives in Linux. Making a mistake during the operation could result in data loss.

Ordinary users are not allowed to perform dangerous fdisk operations. Therefore, it is necessary to log in as the Superuser (root) to carry out partitioning. If the physical machine is not accessible, or BIOS information is unavailable, sometimes it is not known how many hard drives are present inside the PC. In such cases, the fdisk -l option can be used to list the hard drive information.

Example: (logged in as root)
# fdisk -l ←List hard drive information

Disk /dev/sda: 21.4 GB, 21474836480 bytes ←First hard drive /dev/sda
255 heads, 63 sectors/track, 2610 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Disk identifier: 0x000243c8

Device Boot      Start         End      Blocks   Id  System
/dev/sda1   *           1          25      200781   83  Linux ←* denotes the boot partition
/dev/sda2              26         662     5116702+  83  Linux
/dev/sda3             663         789     1020127+  82  Linux swap / Solaris
/dev/sda4             790        2610    14627182+   5  Extended
/dev/sda5             790        2610    14627151   83  Linux

Disk /dev/sdb: 21.4 GB, 21474836480 bytes ←Second hard drive /dev/sdb
255 heads, 63 sectors/track, 2610 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Disk identifier: 0x00000000

Disk /dev/sdb doesn't contain a valid partition table ←/dev/sdb is a new, unpartitioned hard drive

The fdisk command can list how many partitions are created on a hard drive. In the example above, the first hard drive "/dev/sda" is divided into five partitions, named "/dev/sda1" to "/dev/sda5". However, fdisk does not provide information about the mounted partitions. To identify the mount points of "/dev/sda1" to "/dev/sda5", one needs to cross-reference with the information provided by the df command.

If a hard drive is new and unpartitioned, like the second hard drive "/dev/sdb" in the example, it does not have any partition numbers (e.g., "/dev/sdb1"). Next, let's demonstrate how to partition this hard drive.

To operate on a specific hard drive, you can add the hard drive device file after the "fdisk" command. If you are unsure about the device file name for your Linux system, whether it is "/dev/sda" or "/dev/hda," you can use either the fdisk -l or ls /dev/[sh]d command to confirm.[Note]

Example: (logged in as root)
# ls /dev/[sh]d* ←List all available hard drives or partitions
/dev/sda /dev/sda1 /dev/sda2 /dev/sda3 /dev/sda4 /dev/sda5 /dev/sdb

In the example provided, the output lists available hard drives and partitions, such as "/dev/sda", "/dev/sda1", "/dev/sda2" and so on. For instance, "/dev/sda" refers to the whole hard drive, while "/dev/sda1", "/dev/sda2" etc., are individual partitions on that hard drive.

The output also includes "/dev/sdb," which has no number appended (e.g., "/dev/sdb1"). This indicates that no partition has been created on this hard drive yet. To partition this hard drive, you can proceed with the following steps:

Example: (logged in as root)
# fdisk /dev/sdb
Device contains neither a valid DOS partition table, nor Sun, SGI or OSF disklabel
Building a new DOS disklabel with disk identifier 0x9939c1b3.
Changes will remain in memory only, until you decide to write them.
After that, of course, the previous content won't be recoverable.


The number of cylinders for this disk is set to 2610.
There is nothing wrong with that, but this is larger than 1024,
and could in certain setups cause problems with:
1) software that runs at boot time (e.g., old versions of LILO)
2) booting and partitioning software from other OSs
(e.g., DOS FDISK, OS/2 FDISK)
Warning: invalid flag 0x0000 of partition table 4 will be corrected by w(rite)

Command (m for help): ←For a list of available commands, press <m>

Operating fdisk can be extremely dangerous, so at any time, you can press 'm' (m for manual) to display a simple explanation of the available commands. During the operation, all changes are only made in RAM, and as long as you don't press 'w' to write the partition table, you can safely press 'q' to quit fdisk. The command explanations after pressing 'm' are as follows:

Example: (Entering fdisk and then pressing 'm') (The operation screen may vary slightly in different versions)
Command (m for help): m
Command action
a   toggle a bootable flag
b   edit bsd disklabel
c   toggle the dos compatibility flag
d   delete a partition
l   list known partition types
m   print this menu
n   add a new partition
o   create a new empty DOS partition table
p   print the partition table
q   quit without saving changes
s   create a new empty Sun disklabel
t   change a partition's system id
u   change display/entry units
v   verify the partition table
w   write table to disk and exit
x   extra functionality (experts only)

If you want to clear any existing partitions on the hard drive, you can use 'o' to create an empty DOS partition, which will clear all existing partitions and start anew. Now, let's demonstrate how to create a new Linux partition.

(Fdisk operation)
Command (m for help): n ←Create a new partition
Command action
e   extended ←Create an extended partition
p   primary partition (1-4) ←Create a primary partition
p ←Press <p> to create a primary partition
Partition number (1-4): 1 ←Enter the number for the new primary partition
First cylinder (1-2610, default 1):↵ Enter ←Press <Enter> to use the default value for the starting cylinder
Using default value 1
Last cylinder or +size or +sizeM or +sizeK (1-2610, default 2610): +10000M ←Enter the ending cylinder or size for this partition (you can input "+xxxG" or "+xxxM" for size) or press <Enter> to allocate all remaining space.

Command (m for help): p ←Display the current partition table to confirm

Disk /dev/sdb: 21.4 GB, 21474836480 bytes
255 heads, 63 sectors/track, 2610 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Disk identifier: 0x378a1ba0

Device Boot      Start         End      Blocks   Id  System
/dev/sdb1               1        1217     9775521   83  Linux

Command (m for help): w ←Write the partition table and exit
The partition table has been altered!

Calling ioctl() to re-read partition table.
Syncing disks.
You have new mail in /var/spool/mail/root

The size of a partition on a hard drive is calculated as the product of the number of cylinders, heads, sectors, and 512 bytes. However, you don't need to calculate it manually while partitioning; let fdisk handle the conversion for you. For example, when you use 'n' to create a new partition, you'll be prompted to enter the starting cylinder. Pressing <Enter> will use the default value, and then you can input "+sizeG" or "+sizeM" to specify the size of the partition, or simply press <Enter> to allocate all the remaining space to this partition.

If you make any changes to the partition, you'll need to restart the system, as Linux kernel loads the partition table only during boot-up. While you can use the partprobe command to force the kernel to update the partition table, it's safer to restart the system after any changes to the partitions.

The example only demonstrates creating one primary partition, but if you're interested, you can experiment with deleting partitions or adding more primary/extended partitions to become more familiar with the process.

During the partitioning process, you can press 'p' to display the current partition table, and if you want to create non-Linux partitions, you can use 't' to change the partition ID. Pressing 'l' (lowercase L) will list all the supported partition types and their IDs.



^ back on top ^

Modern GPT Disk Partitioning
New GPT (GUID Partition Table) disk partitioning was mainly introduced to overcome the limitations of MBR disk partitioning, which cannot exceed 2.19 TB and only supports up to 4 primary partitions. GPT, on the other hand, supports much larger disk sizes, up to an astronomical 18 exabytes (1 EB = 1024 PB).

Traditional BIOS reads the MBR (Master Boot Record) of the disk during boot-up, and due to the limitations of MBR, partitions cannot exceed 2 TB, which becomes inadequate for modern requirements.

To replace the old BIOS, Intel led the development of a new interface called "EFI" (Extensible Firmware Interface), also known as UEFI (Unified Extensible Firmware Interface). EFI redefines the disk partition table and boot process.

One of the advantages of GPT is that it eliminates the limitations of MBR's maximum four primary partitions. As a result, there is no need for extended partitions and logical partitions. Thus, a single hard drive can have more than four operating systems installed as bootable partitions, and each partition can exceed 2.19 TB in size.




^ back on top ^

Using parted to partition disks
Parted is a disk partitioning tool released by GNU. The name "parted" is a combination of "partition" and "editor," indicating its purpose of editing partitions. parted supports both MBR and GPT partition tables, as well as Apple computers' Mac partition table.

As hard drives continue to grow in size, using GPT for partitioning and adopting advanced formatting for hard drives and SSDs has become an irreversible trend. parted provides more support than fdisk and is recommended to replace the outdated fdisk.

Parted can be used in interactive mode and command-line mode. The interactive mode is more user-friendly and less error-prone, while the command-line mode is faster and suitable for bulk and quick operations.



^ back on top ^

partprobe : Reload Partition Table
Since the Linux kernel only loads the disk partition table during boot, if you change the partition using fdisk or parted without rebooting, you can use the partprobe (partition probe)tool to reload the disk partition.

A common option is "-s" to display a summary of partition content.

Example:
# partprobe -s ←Display a summary of partition content
/dev/sda: gpt partitions 1 2 3 4 5
/dev/sdb: gpt partitions 1 2 3 5 6 7 8 9 4


^ back on top ^



  1.3 Formatting File Systems

After partitioning with tools like fdisk or parted, partitions need to be formatted before they can be used properly. The file system used for formatting should match the filesystem type (ID) set for the partition during partitioning. For example, if parted is used to set the filesystem type to ext2, the partition can be formatted as ext2, ext3, or ext4, but not as FAT32 or any other file system, as compatibility issues may arise.

The reason for formatting partitions with ext2/ext3/ext4 file systems is that formatting involves allocating inodes and specifying block sizes. If there were data in the original filesystem, it will be erased after formatting. Therefore, caution should be exercised during formatting, and only the superuser (root) can perform this operation. The commonly used formatting tool in Linux is mkfs.




mkfs : Format the filesystem
mkfs is a front-end program, meaning it acts as a shell to provide a consistent interface for formatting different file systems. For example, using mkfs -t vfat will format the file system as FAT32. In reality, it executes the program mkfs.vfat. Similarly, mkfs -t ext2 executes mkfs.ext2. If you're unsure which file systems your system supports for formatting, you can use the command ls /sbin/mkfs.* to check.

Please note that you cannot format a partition that is already mounted.

Example:
# ls /sbin/mkfs.* ←heck which file systems are supported for formatting
/sbin/mkfs.btrfs /sbin/mkfs.ext3 /sbin/mkfs.minix /sbin/mkfs.xfs
/sbin/mkfs.cramfs /sbin/mkfs.ext4 /sbin/mkfs.msdos
/sbin/mkfs.ext2 /sbin/mkfs.fat /sbin/mkfs.vfat /sbin/mkfs.exfat

The mkfs command can format a wide range of mainstream file systems. Here is the general usage of the mkfs command:
Syntax: mkfs [-otpiton] [fs][-option] device
Command name/function/command user Options Function
mkfs/
 format filesystem/
root
-t Specifies the formatted file system, commonly used as follows:
ext2, ext3 or ext4: Linux native file system.
ntfs: Windows NT, the file system above XP.
vfat: Supports FAT with long file names (FAT32).
exfat: exFAT
xfs: a log-type high-efficiency file system
msdos: only supports FAT with 8.3 file names.
-b Specifies the block size (not applicable to vfat/msdos/ntfs).
-L Set the partition label (not applicable for vfat/msdos/ntfs).
fs The options that can be connected after "fs" are as follows:
-c: Check to see if there is any bad track and then format.
-l: (lowercase L) read the file output by badblocks .
-v: Display the formatting process


Example:
# mkfs /dev/sdb1 ←If no options are specified, the default formatting filesystem is ext2
# mkfs -t ext4 /dev/sdb ←Format as ext4
# mkfs -t ext3 -b 2048 -L DB /dev/sdb2 ←Format as ext3 with a block size of 2048, and label it as "DB"
# mkfs fs -c /dev/sdb1 ←Check for bad blocks before formatting
# mkfs -t vfat /dev/sdc1 ←Format as FAT32
# mkfd -t msdos /dev/fd0 ←Format the floppy disk as msdos

^ back on top ^

tune2fs : Adjust ext filesystem settings
When files are damaged, upgrading to ext3 from ext2 is recommended because ext3 offers better chances of recovery. You can seamlessly and safely upgrade from ext2 to ext3 using tune2fs -j.

This information was last updated on : Aug 15 2020
tune2fsversions 1.41.0 and above support upgrading from ext3 to ext4. . [Note 1.3]


Example:
# tune2fs -j /dev/sdb1 ←Upgrades /dev/sdb1 from ext2 to ext3

tune2fs can be used not only for filesystem upgrades but also to configure how often to check ext2/ext3/ext4 filesystems. There are two ways to check: using tune2fs -c to set the number of mounts before an automatic check, and using tune2fs -i to set the time interval for checks. Below are the detailed options and usage:
Syntax: tune2fs [-otpiton] device
Command name/function/command user Options Function
tune2fs/
tune to filesystem/
root
-l: (lowercase L) Lists filesystem superblock and other information.
-c # Sets the number of mounts before an automatic filesystem check (# is a number; set to 0 or -l to disable).
-i#[dmw] Sets the time interval for automatic filesystem checks (# is a number; set to 0 or -l to disable; d for days, m for months, w for weeks).
-m # Reserves a percentage of blocks for the system (# is a number; the default is usually 5%).
-r # Sets the number of reserved blocks (# is a number).
-j Converts ext2 to ext3.
-L Sets the partition label (similar to e2label or mkfs -L).
-o Additional mount options.

例:
# tune2fs -L "share" /dev/sdb1 ← Sets the label of /dev/sdb1 to "share"
# tune2fs -l /dev/sda2 | grep "Last mount" ← Checks the last mount time
# tune2fs -m 10 /dev/sdb1 ← Reserves 10% of blocks
# tune2fs -i 3m /dev/sdb1 ← Checks the filesystem after three months
# tune2fs -c 100 /dev/sdb1 ← Sets automatic check after 100 mounts
# tune2fs -c -1 /dev/sdb1 ← Disables automatic check on mounts

^ back on top ^

e2label : Set the label of a filesystem
To easily identify a filesystem (usually associated with a single partition), you can assign a label name to it. For ext2/ext3 or ext4 filesystems, you can use e2label to set a label name. The syntax is: e2label device [label_name]. The label name cannot exceed 16 characters. If you omit the label name, the existing label will be displayed.

Example:
# e2label /dev/sdc1 ← Display the current label
lab_data
# e2label /dev/sdc1 "hello world" ← Set the label of /dev/sdc1 to "hello world"

For FAT filesystems, the commands to set the label are dosfslabel or mlabel -i.

For more information on e2label operations and examples, please refer to the provided link .

^ back on top ^

fsck : Check and attempt to repair the filesystem
The command fsck is used to check and attempt to repair file systems. It is executed when the system experiences sudden power loss, software crashes, or forced reboots due to unclean shutdowns. When the file system is not properly unmounted before a reboot, the system automatically runs the fsck command.

fsck is a front-end program similar to mkfs and performs file system checks and repairs specific to different file systems like ext2, ext3, ext4, vfat, or e2fsck. You can check the supported file systems by running the command ls /sbin/fsck.*.

During startup, the system may automatically run fsck based on mount counts or mount intervals to determine whether file system checks and repairs are needed. This information can be displayed using the tune2fs -l DEVICE command.

It's important to note that running fsck on a mounted file system can result in data corruption. Therefore, it's essential to unmount the file system before using fsck for checking and repair.

You can specify the file system to be checked by using either the device file (e.g., fsck /dev/sda2) or the mount point (e.g., fsck /home).

For automatic checks on partitions listed in "/etc/fstab", you can use fsck -A. The "-AR" option is similar to "-A" but excludes the root directory, often used to check all partitions except the root directory.

To illustrate further, here are some examples:
# umount /home
# fsck /home

Running "fsck" on partitions listed in "/etc/fstab":

# init 1
# umount -a
# fsck -AR

Other options:

UNIX directory structure observation reveals that crucial directories like "/bin" and "/dev" are on the same partition as the root "/", making it impossible to unmount the root directory. To address this, the highest priority for checking is assigned to the root partition in "/etc/fstab". If needed, a forced fsck check can be triggered using shutdown -rF now.

Please note that these commands and instructions are based on Linux file system maintenance.


^ back on top ^

1.4 Mounting Filesystems

When working with Windows, connecting recognized filesystems like hard drives, CDs, floppies, or USB flash drives automatically results in their immediate "mounting," making them readily accessible. This behavior seems natural and expected. However, in the UNIX world, the process is quite different. Adding new storage media requires system administrator intervention to "mount" them before they can be accessed. (If authorized, regular users can also perform mount and umount operations by setting the "user" option in the "/etc/fstab" file.)

In modern Linux distributions, such as Fedora or CentOS, the approach to mounting storage media falls between that of Windows and UNIX. For instance, when running graphical interfaces (e.g., GNOME desktop environment), recognized filesystems on CD-ROMs, USB flash drives, or hard drives are automatically mounted. However, if you log in through a text interface, the UNIX tradition of not automatically mounting new filesystems is retained.

While automated mounting of storage media offers convenience, it also poses security risks. For example, if sensitive data is on a disk and it's automatically mounted, anyone can access its contents, undermining security. As a result, many Linux servers are configured to boot and operate in runlevel 3 (init = 3), a text-based mode. In this mode, filesystems need to be manually "mounted" by a system administrator before their contents can be accessed.

Due to the interference caused by the "gnome-volume-manager," which automatically mounts new storage media in the Fedora/CentOS GNOME desktop environment, the subsequent explanations and operations will revert to a more basic text-based approach. To achieve this, edit the "/etc/inittab" file and locate the line "id:5:initdefault:". Change it to "id:3:initdefault:" and then restart. This change ensures the system logs in to runlevel 3, the text-based interface, on reboot. This approach aims to closely replicate the original UNIX operations.

(Note: This information was last updated on June 17, 2019.)

In newer versions of Fedora/CentOS (like CentOS 7 or later), the concept of "target" is introduced to replace the use of the configuration file "/etc/inittab" for setting the runlevel during boot. Different boot modes (targets) can be configured using systemctl.

Example: (For CentOS 7/CentOS 8)
# systemctl set-default graphical.target  ← Set graphical mode boot (default runlevel = 5)
# systemctl set-default multi-user.target ← Set text-based boot (runlevel = 3, requires a reboot)
#
# systemctl get-default ← View the current default mode
# systemctl list-units --type=target ← View available targets

When mounting a filesystem, you need to specify a directory as the mount point. Once successfully mounted, any pre-existing data in the directory becomes temporarily hidden to display the contents of the mounted filesystem. This behavior remains until the filesystem is unmounted, at which point the original data becomes visible again. Traditionally, the "/mnt" directory is used as a temporary mount point, while "/media" is used for removable media mount points. 。

^ back on top ^



^ back on top ^





   
[Note] The traditional IDE hard disk device files were named as "/dev/hd[a~d]", but starting from Linux Kernel version 2.6.19, the device naming for both IDE (PATA) and SATA hard disks was unified, and they are now uniformly named as "/dev/sd[a~p]".

[Note 1.3] You can upgrade an ext3 file system to ext4. Ext4 is backward compatible with ext3, meaning you can mount an ext3 file system as ext4 without any data loss or changes to the file system itself. However, to fully utilize the features of ext4, you should perform a filesystem conversion or upgrade from ext3 to ext4.

To perform the upgrade, follow these steps:

  1. Backup your data: Before making any changes, it is always recommended to back up your data to prevent accidental data loss.

  2. Unmount the ext3 file system: Make sure the ext3 file system is not mounted. You can use the umount command to unmount it if it's currently mounted.

  3. Check the file system: Before upgrading, you should run a file system check on the ext3 file system to ensure there are no errors. You can use the e2fsck command for this:

    e2fsck -f /dev/your_ext3_partition

  4. Convert to ext4: Now, convert the ext3 file system to ext4 using the tune2fs command:

    tune2fs -O extents,uninit_bg,dir_index /dev/your_ext3_partition

  5. Update the file system: Run the fsck command to update the file system's metadata to ext4:

    fsck -pf /dev/your_ext3_partition


  6. Mount the ext4 file system: After the conversion, you can mount the updated ext4 file system: mount /dev/your_ext3_partition /mount_point

Once the conversion is complete, your ext3 file system will be using the ext4 features, such as extents and directory indexing. However, it's essential to note that converting from ext3 to ext4 does not reclaim the space used by the old inode table. If you want to make the most of the ext4 file system, it is recommended to create a new file system from scratch (after backing up your data) rather than converting from ext3.