Practical Linux Disk Management (Partitioning, Formatting, Mounting)

<span>In the Linux system, disk management is a fundamental knowledge point. Properly performing disk partitioning, formatting, and mounting ensures that we can fully utilize disk space and efficiently store and access data.</span>

<span>Compared to the simple drive letter management in Windows systems, disk management in Linux is more complex and flexible. In the Linux system, all devices are stored under the /dev directory, such as disks, keyboards, mice, etc.</span><span>Therefore, to use a disk, we need to perform operations such as partitioning, formatting, and mounting, so that the disk can be mounted to a known folder for normal use.</span>

<span>Before practicing Linux disk management, it is best to understand what disks and file systems are to facilitate quick operations.</span>

<span>This article uses the Linux distribution Ubuntu 23.10, but there will not be much difference with other distributions.</span>▼The main content begins▼▼The main content begins▼🔔

(1): Basic Introduction

Disk partitioning is the process of dividing a physical disk into logical parts. When we purchase a hard drive, it is usually a continuous storage unit referred to as unallocated space. By performing disk partitioning, we can divide the hard drive into multiple logical parts, each referred to as a partition.In the Linux system, various tools can be used for disk partitioning, such as fdisk, gdisk, etc. With these tools, we can select the disk to be partitioned and specify the size, type, and other information of the partition. For example, when partitioning the <span>/dev/sda</span> device, each partition will be assigned a unique device name (such as <span>/dev/sda1</span>, <span>/dev/sdb2</span>, etc.), and can be accessed and managed in the file system.Before partitioning, it is important to understand the size of your disk. For disks under 2TB, both MBR and GPT partitioning can be used, but for disks over 2TB, GPT partitioning must be used;Use fdisk for MBR partition tables, and gdisk for GPT partition tables!

The benefits of disk partitioning include:    1: Space management: By partitioning, we can better organize and manage data on the disk.        - Different partitions can be used to store different types of data, such as operating system files, applications, user data, etc.    2: Data protection: If one partition is damaged or fails, the data on other partitions is usually unaffected.        - This allows us to better protect and recover data.    3: Multi-system support: Disk partitioning can also be used to install multiple operating systems.        - Each operating system can be installed on a different partition and run independently.

(2): fdisk Partitioning Tool

If your disk size is under 2TB, you can use the fdisk command for MBR partitioning. Remember, do not use the fdisk command for disks over 2TB, as you will find that no matter how you partition, it will not exceed 2TB, which means the remaining capacity cannot be used. It is also best to insert another disk into the computer for testing.

I: Install the fdisk command (usually available):    sudo apt-get -y install fdisk   # Install on Ubuntu    sudo yum -y install fdisk       # Install on CentOS
II: Basic syntax of the fdisk command:    fdisk -help         # View the manual    fdisk -l            # View how many disks and partitions exist on the server (can use "| grep xx" to query)    fdisk -l /dev/sdb   # Query the partition of "/dev/sdb"
III: fdisk disk partitioning (first enter the disk, such as entering the /dev/sdb device; fdisk /dev/sdb)    d: Delete a partition    F: List unallocated free space    l: List known partition types (for example, the type of extended partition is 05)    n: Add a new partition    p: Print the partition table    t: Change the partition type (can choose from the types listed by 'l')    v: Check the partition table    i: Print information about a specific partition    m: Print this menu    w: Write the partition table to disk and exit (save the previous partition operations)    q: Exit without saving changes    g: Create a new GPT partition table on the current disk    G: Create an empty GPT (IRIX) partition table on the current disk    o: Create an empty DOS partition table on the current disk (the default for MBR partitioning is DOS)    s: Create an empty Sun partition table on the current disk

Basic Example:Basic Example:

Click Example 1: Perform basic partitioning on the “/dev/sdc” disk device
"Involves the n option" enter the '/dev/sdc' disk    &gt;&gt;  fdisk /dev/sdc    Command (enter m for help): n    # Represents creating a partition    Partition type       p   Primary partition (0 primary, 0 extended, 4 free)       e   Extended partition (logical partition container)    Select (default p): p    Partition number (1-4, default  1): 1    First sector (2048-41943039, default 2048): 2048    Last sector, +/-sectors or +/-size{K,M,G,T,P} (2048-41943039, default 41943039): +2G    Created a new partition 1, type "Linux", size 2 GiB. Note: Regarding '+/-size{K,M,G,T,P}', the size of the partition can be set without writing the end sector size, but directly set to an understandable size, such as +2G, +512M, +128k, etc., which makes it simpler. Note: A maximum of four primary partitions can be created; if multiple partitions are needed, a logical partition must be created within one of the primary partitions, and multiple partitions can be created within that logical partition.
Click Example 2: Delete a partition and change “/dev/sdc3” to a FAT12 partition
# Below are several test partitions I created;# It can be seen that the /dev/sdc4 partition is an extended partition, which exactly wraps around sdc5~sdc7# These 3 partitions are actually created within the logical partition of sdc4    Device       Boot     Start     End     Sectors Size Id Type    /dev/sdc1           2048  4196351  4194304   2G 83 Linux    /dev/sdc2        4196352 12584959  8388608   4G 83 Linux    /dev/sdc3       12584960 23070719 10485760   5G 83 Linux    /dev/sdc4       23070720 62914559 39843840  19G  5 Extended    /dev/sdc5       23072768 35655679 12582912   6G 83 Linux    /dev/sdc6       35657728 44046335  8388608   4G 83 Linux    /dev/sdc7       44048384 62914559 18866176   9G 83 Linux# To delete a partition, simply use the d option    Command (enter m for help): d    Partition number (1-7, default  7): 7     # The values 1-7 here represent the selectable partitions    Partition 7 has been deleted.# To change the partition type, directly use the t option    Command (enter m for help): t    Partition number (1-6, default  6): 3     # Select the partition to change    Hex code or alias (type L to list all): l  # Entering L will print the available partition types, find the hexadecimal partition number    Hex code or alias (type L to list all): 05 # 05 represents the hexadecimal number for FAT12# Use the t option to see how much unallocated space is left    Command (enter m for help): F    Unallocated space /dev/sdc: 9 GiB, 9659482112 bytes, 18866176 sectors    Units: sectors / 1 * 512 = 512 bytes    Sector size (logical/physical): 512 bytes / 512 bytes        Start     End     Sectors Size    44048384 62914559 18866176   9G
Click Example 3: Use the p option to view partition information
# Use the p option to view partition information      Disk /dev/sdc: 30 GiB, 32212254720 bytes, 62914560 sectors    Disk model: VMware Virtual S    Units: sectors / 1 * 512 = 512 bytes    Sector size (logical/physical): 512 bytes / 512 bytes    I/O size (minimum/best): 512 bytes / 512 bytes    Disk label type: dos    Disk identifier: 0x1d3d3a3d    Device       Boot     Start     End     Sectors Size Id Type    /dev/sdc1           2048  4196351  4194304   2G 83 Linux    /dev/sdc2        4196352 12584959  8388608   4G 83 Linux    /dev/sdc3       12584960 23070719 10485760   5G  1 FAT12    /dev/sdc4       23070720 62914559 39843840  19G  5 Extended    /dev/sdc5       23072768 35655679 12582912   6G 83 Linux    /dev/sdc6       35657728 44046335  8388608   4G 83 Linux

PrecautionsPrecautions:

  • When using the fdisk command, please operate carefully and ensure the correct selection of the device file name.

  • Before performing partition operations on the disk, be sure to back up important data to prevent data loss.

  • If you encounter the error message <span>bash: fdisk: command not found</span>, it means the fdisk command is not installed.

(3): gdisk Partitioning Tool

Since the fdisk command does not support GPT partitioning well, and MBR partitioning does not support partitions larger than 2TB, for partitioning disks over 2TB, GPT partitioning must be used, so the gdisk command is required; gdisk can also handle MBR partitioned disks, regardless of the size of the disk.

I: Install the gdisk command (usually available):    sudo apt-get -y install gdisk   # Install on Ubuntu    sudo yum -y install gdisk       # Install on CentOS
II: Basic syntax of the gdisk command:    gdisk device_name    Example: gdisk /dev/sdf        # Partition the '/dev/sdf' disk, note that there are no numbers after the device (numbers indicate already partitioned disks, use lsblk to view disks)
III: gdisk disk partitioning (first enter the disk before executing these options)    b: Backup GPT data to a file    c: Change the name of the partition    d: Delete a partition    i: Display detailed information about the partition    l: List known partition types    n: Add a partition    o: Create a new empty GUID partition table (GPT)    p: Print the partition table    q: Exit without saving    r: Recovery and conversion options (for experts only)    s: Sort partitions    t: Change the partition type    v: Verify the disk    w: Write the partition table to disk and exit (save the previous partition operations)    x: Extra features (for experts only)    ?: Print menu

Basic Example:Basic Example:

Click Example 1: Enter the disk of “/dev/sdf” and add a partition
"[Enter the disk to be partitioned]"    &gt;&gt; gdisk /dev/sdf        GPT fdisk (gdisk) version 1.0.9        Partition table scan:          MBR: protective          BSD: not present          APM: not present          GPT: present        'Scanned the GPT partition table, if GPT: not present, you can use the o option to reset'
"[Add partition n option]"    &gt;&gt; Command (? for help): n        'Partition number (1-128, default 1); a maximum of 128 partitions can be created'            Partition number (1-128, default 1):        'Set the starting sector'            First sector (34-8589934558, default = 2048) or {+-}size{KMGTP}: 2048        'Set the ending sector (we do not need to calculate the sector number ourselves, using the +capacity method)'        'Using the +capacity method, gdisk actively calculates the closest sector number needed for you.'            Last sector (2048-8589934558, default = 8589932543) or {+-}size{KMGTP}: +1G        'Current partition type is 8300 (Linux filesystem), specific types can be queried using L'            Current type is 8300 (Linux filesystem)        'Set the desired hexadecimal code or GUID type (default 8300, can use L to query)'            Hex code or GUID (L to show codes, Enter = 8300):8300        'Changed the partition type to "Linux filesystem"'
##### Special Note #####'    1: Do not use the default value in the Last sector line! The default value will use up all the capacity! Because the default selects the largest sector number!        We can set it using +G, +M, +K, +T, etc., so I added +1G to represent a partition of 1GB,        without needing to calculate the number of sectors, gdisk will calculate based on the value you fill in.    2: The common partition types in Linux are generally 8200/8300/8e00, while Windows mostly uses 0700; if you forget these,        you can press L in gdisk to display the types; here are a few common ones:            8200 (swap partition)      8300 (ordinary Linux filesystem)    8e00 (extended LVM logical volume)
Click Example 2: Querying partitions
"[Output the current disk status p option]"    &gt;&gt; Command (? for help): p        'Disk file name: total sectors, disk capacity'            Disk /dev/sdf: 8589934592 sectors, 4.0 TiB        'Currently a virtual machine disk (not a real 4T physical disk)'            Model: VMware Virtual S        'Each sector size is 512 bytes'            Sector size (logical/physical): 512/512 bytes        'Disk GPT identifier'            Disk identifier (GUID): D3DD6483-3414-4722-BAE4-8A4B608172E7        'The partition table can hold up to 128 entries'            Partition table holds up to 128 entries        'Main partition table begins at sector 2 and ends at sector 33'            Main partition table begins at sector 2 and ends at sector 33        'The first usable sector is 34, the last usable sector is 8589934558'            First usable sector is 34, last usable sector is 8589934558        'Partitions will be aligned on 2048-sector boundaries'            Partitions will be aligned on 2048-sector boundaries        'Total available space is 8589934525 sectors (4.0 TiB)'            Number  Start (sector)    End (sector)  Size       Code  Name               1            2048         2099199   1024.0 MiB  8300  Linux filesystem               2         2099200         6293503   2.0 GiB     0700  Microsoft basic dataThe lower part of the partition table mainly lists individual information for each partition slot, as follows:    Number: Partition slot number, number 1 refers to /dev/sdf1    Start (sector): The starting sector number position of each partition slot    End (sector): The ending sector number position of each partition, the total capacity of the partition slot can be calculated between start and end    Size: The capacity of the partition slot    Code: Possible filesystem types within the partition slot. Linux is 8300, swap is 8200.        'Note: However, this type is just a hint and does not necessarily represent the actual filesystem within this partition slot!'    Name: The name of the filesystem, etc. From the above table, we can find several things:    The entire disk can still be partitioned further, as the maximum sector is 8589934558, but only up to sector 6293503 is used.    In the design of partition slots, new partitions usually choose the end sector number of the previous partition plus 1 as the starting sector number!
Click Example 3: Deleting and saving
"[Partition deletion]"&gt;&gt; Command (? for help): d  Partition number (1-2): 1 # Can choose to delete the two already partitioned, after deletion use p option to view  "[Partition saving]"&gt;&gt; Command (? for help): w  Final checks complete. About to write GPT data. THIS WILL OVERWRITE EXISTING PARTITIONS!!  Do you want to proceed? (Y/N):y  OK; writing new GUID partition table (GPT) to /dev/sdf.  The operation has completed successfully.

(4): Observing Disk Partition Status

1: lsblk Command

The lsblk command actually lists all disk lists on the system (full name: List Block Device)

"Syntax:"    &gt;&gt; lsblk [-options] [device]        Options and parameters:            -d: Only list the disk itself, and will not list the partition data of that disk            -f: Also list the filesystem name within that disk            -i: Use ASCII line output, do not use complex encoding (useful in some environments)            -m: Also output the permission data of the device under /dev (rwx data)            -p: List the full file name of the device! Instead of just listing the last name.
            -t: List detailed data of the disk device, including disk queue mechanism, pre-read/write data size, etc."Example 1: List all disks and partition information under this system"    &gt;&gt; lsblk        NAME   MAJ:MIN RM   SIZE RO TYPE MOUNTPOINT        sda      8:0    0    20G  0 disk        ├─sda1   8:1    0     1M  0 part        └─sda2   8:2    0    20G  0 part /var/snap/firefox/common/host-hunspell                                         /    # Mounted to the root directory        sdb      8:16   0    20G  0 disk    # It can be seen that the sdb disk is divided into 2 partitions (used 7G partition)        ├─sdb1   8:17   0     5G  0 part        └─sdb2   8:18   0     2G  0 part        sdc      8:32   0    60G  0 disk    # A complete unpartitioned disk of 60G        sdd      8:48   0    30G  0 disk        sde      8:64   0    40G  0 disk        sdf      8:80   0     4T  0 disk        └─sdf2   8:82   0     2G  0 part        sr0     11:0    1  1024M  0 rom"Directory Introduction:"    NAME: The device file name. The leading directory like /dev will be omitted!    MAJ:MIN: The device is recognized through these two codes! They are the major and minor device codes!    RM: Whether it is a removable device (removable device), such as a CD, USB disk, etc.    SIZE: Disk or partition capacity    RO: Whether it is a read-only device    TYPE: Is it a disk (disk), partition slot (partition), or read-only memory (rom) etc. output    MOUNTPOINT: Mount point!

2: blkid Command

The blkid command lists the UUID and other parameters of the device (full name: Block Id); although lsblk can already use -f to list filesystem and device UUID data, using blkid directly to find the device’s UUID is more convenient; UUID is a globally unique identifier, and Linux assigns a unique identifier to all devices in the system, which can be used for mounting or using this setting or filesystem.

3: parted Command

The parted command lists the partition table type and partition type of the disk (we will not discuss its partitioning here)

Syntax:    &gt;&gt; parted device_name printExample (list information of /dev/sdb1 disk):    &gt;&gt; parted /dev/sdb1 print        Model: VMware, VMware Virtual S (scsi)  'Disk module name (vendor)'        Disk /dev/sdb: 21.5GB                  'Total capacity of the disk'        Sector size (logical/physical): 512B/512B         'Capacity of each logical/physical sector'        Partition table: msdos                          'Partition table format (MBR/GPT), at this time msdos can be considered MBR'        Disk flags:            Number   Start   End   Size     Type      Filesystem  Flags             1    1049kB  5370MB  5369MB  primary   ext3             2    5370MB  7517MB  2147MB  primary   ext3             3    7517MB  9665MB  2147MB  primary   ext3             4    9665MB  21.5GB  11.8GB  extended             5    9666MB  12.9GB  3221MB  logical   ext2             6    12.9GB  14.0GB  1074MB  logical   ext3             7    14.0GB  17.2GB  3221MB  logical             8    17.2GB  19.3GB  2147MB  logical             9    19.3GB  21.5GB  2141MB  logical

(1): Basic Introduction

Formatting is the operation performed on a partition after partitioning the disk, preparing it for data storage. Formatting will erase all data in that partition and create a new filesystem on the disk so that the operating system can correctly read and write data. The essence of partition formatting is to create a filesystem on the partition; a filesystem is a way to organize and access data, including the structure of files and directories, data storage and retrieval, as well as management of permissions, attributes, and metadata. Common filesystem types include NTFS and FAT32 supported by Windows, while Linux supports ext4 and XFS, etc.; we need to create different filesystems according to actual needs.Formatting is essentially creating a filesystem (make filesystem), so the command for creating a system is <span>mkfs</span>, which is a comprehensive command; when we create an ext4 filesystem, it should be written as <span>mkfs -t ext4 device_number</span>, which essentially calls the <span>mkfs.ext4</span> command, and we can also write it directly as <span>mkfs.ext4 device_number</span> (recommended) to create directly.

'View the filesystem commands that the system can support for creation:'    &gt;&gt; mkfs [tab key] [tab key]             mkfs        mkfs.bfs    mkfs.cramfs     mkfs.ext2       mkfs.ext3   mkfs.ext4           mkfs.fat    mkfs.minix  mkfs.msdos      mkfs.ntfs       mkfs.vfat'What is printed above is the filesystems that can be created, you can use mkfs -t or directly use mkfs.xxx'You can also query as follows:'    &gt;&gt; ll /sbin/mkfs.*        -rwxr-xr-x 1 root root 22912 10月  6 05:27 /sbin/mkfs.bfs*        -rwxr-xr-x 1 root root 35144 10月  6 05:27 /sbin/mkfs.cramfs*        lrwxrwxrwx 1 root root     6  7月 27 02:26 /sbin/mkfs.ext2 -&gt; mke2fs*        lrwxrwxrwx 1 root root     6  7月 27 02:26 /sbin/mkfs.ext3 -&gt; mke2fs*        lrwxrwxrwx 1 root root     6  7月 27 02:26 /sbin/mkfs.ext4 -&gt; mke2fs*        -rwxr-xr-x 1 root root 52048  3月 23  2022 /sbin/mkfs.fat*        -rwxr-xr-x 1 root root 43408 10月  6 05:27 /sbin/mkfs.minix*        lrwxrwxrwx 1 root root     8  3月 23  2022 /sbin/mkfs.msdos -&gt; mkfs.fat*        lrwxrwxrwx 1 root root     6  2月 15  2023 /sbin/mkfs.ntfs -&gt; mkntfs*        lrwxrwxrwx 1 root root     8  3月 23  2022 /sbin/mkfs.vfat -&gt; mkfs.fat*'In fact, we can find that the mkfs.ext2 command is a soft link to the mke2fs command, and the mkfs.ntfs command is a soft link to mkntfs.'For example: mke2fs is equivalent to using mkfs.ext2'

From the above, we can see that both <span>mkfs</span> and <span>mke2fs</span> are commands used to create filesystems, see the following explanation.

(2): mkfs Creating Filesystem

<span>mkfs</span> is a general command used to create various types of filesystems, which can be created according to the specified filesystem type. It can create filesystems such as ext2, ext3, ext4, bfs, ntfs, etc. The mkfs command provides a wider range of options and functions, suitable for different operating systems and scenarios. However, it is generally not recommended to use the <span>mkfs -t filesystem</span> command directly, but to use commands like <span>mkfs.ext4</span> instead.

1: mkfs.ext2~4 Command

'mkfs.ext2, mkfs.ext3, mkfs.ext4 syntax:'    [-c|-l filename] [-b block size] [-C cluster size] [-i bytes per inode] [-I inode size] [-J journal options]        [-G flexible group size] [-N number of inodes] [-d root directory] [-m percentage of reserved blocks] [-o origin system name]        [-g number of blocks per group] [-L volume label] [-M last mount point] [-O features[,...]] [-r filesystem version]        [-E extended options[,...]] [-t filesystem type] [-T usage type] [-U UUID] [-e error behavior][-z undo file]        [-jnqvDFKSV] device [block number]    Parameter details:        -c: Check for bad blocks before creating the filesystem        -b: Set the logical block size within the filesystem (e.g., 1k, 2k, 4k; but the maximum for Linux is 4K)        -L: Set the filesystem volume label (the volume can be mounted using the label later)        -j: Create an ext3 journal filesystem, mkfs.ext3 comes with this option;        -m: Percentage of reserved blocks, which is reserved for administrator disk blocks (parameter is a number, do not add %)        -i: Specify the number of bytes per inode, but must be an integer multiple of the block size unit        -U: Set the UUID of the filesystem within the disk partition (must write a standard UUID)        'The following command basic usage description:'    1: Although using mkfs.ext2 is a non-journal system, adding -j will force it to become an ext3 filesystem    2: mkfs.ext2 is equivalent to mkfs -t ext2'Command:'    &gt;&gt; mkfs.ext2 -b 2k -L demoTest -j /dev/vdb1        mke2fs 1.46.5 (30-Dec-2021)        /dev/vdb1 has an ext3 filesystem                Created on Fri Jan 19 23:41:00 2024        Do you want to continue anyway? (y,N) y        Creating a filesystem with 1048576 blocks (each block 2k) and 131072 inodes        Filesystem UUID: a94d46ba-4f33-4ab3-9cd4-cfee31e78367        Backup of the superblock is stored in the following blocks:                16384, 49152, 81920, 114688, 147456, 409600, 442368, 802816        Allocating group table: done        Writing inode table: done        Creating journal (16384 blocks): done        Writing superblock and filesystem accounting statistics: done            &gt;&gt; blkid /dev/vdb1          /dev/vdb1: LABEL="demoTest" UUID="a94d46ba-4f33-4ab3-9cd4-cfee31e78367"        SEC_TYPE="ext2" BLOCK_SIZE="2048" TYPE="ext3" PARTUUID="1c2f79e7-01"

(3): mke2fs Creating Filesystem

<span>mke2fs</span> is a specific implementation of mkfs, specifically providing a specialized tool for ext filesystems. It is a derivative command of mkfs.ext2, mkfs.ext3, mkfs.ext4, and its usage is the same as these commands.

'If you use mke2fs directly, it defaults to creating an ext2 filesystem'Explanation:    Create an ext type filesystem on /dev/vdb2, and specify it as an ext3 journal filesystem,      with a logical block size of 2K, inode byte size of 4K, and a reserved block percentage of 5%'Command:'    &gt;&gt; mke2fs -j -b 2048 -m 5 -i 4096 /dev/vdb2        mke2fs 1.46.5 (30-Dec-2021)        /dev/vdb2 has an ext3 filesystem                Created on Fri Jan 19 23:41:22 2024        Do you want to continue anyway? (y,N) y        Creating a filesystem with 524288 blocks (each block 2k) and 262144 inodes        Filesystem UUID: 456fbfb6-cbab-45c3-a0a9-36e89ee755f1        Backup of the superblock is stored in the following blocks:                16384, 49152, 81920, 114688, 147456, 409600, 442368        Allocating group table: done                                    Writing inode table: done                                    Creating journal (16384 blocks): done        Writing superblock and filesystem accounting statistics: done        'I found that I did not use -L to set the volume label, which can actually be set later:    'e2label' command to set the volume label, as follows:        e2label  /dev/vdb2           View volume label        e2label  /dev/vdb2 demoLabel Set volume label

(4): Viewing or Adjusting Filesystem Information

1: tune2fs Command

1: View detailed information about the filesystem of the specified device:
    tune2fs -l /dev/sdb
2: Set the maximum number of times the filesystem can be mounted before a forced check:
    tune2fs -c 15 /dev/sdb
3: Set to automatically check the filesystem after 10 days:
    tune2fs -i 10d /dev/sdb
4: Set to automatically check the filesystem after 3 weeks:
    tune2fs -i 3w /dev/sdb
5: Set to automatically check the filesystem after 6 months:
    tune2fs -i 6m /dev/sdb
6: Add journal functionality, converting ext2 to ext3 filesystem:
    tune2fs -j /dev/sdb
7: Set the reserved space of the specified disk partition filesystem to 40000 disk blocks:
    tune2fs -r 40000 /dev/sdb

2: dumpe2fs Command

This command is a command-line tool for displaying detailed information about ext2, ext3, ext4 filesystems. It can display information such as the superblock, block group descriptors, inode table, directory structure, block bitmap, inode bitmap, etc.

Syntax:    dumpe2fs [-bfghimxV] [-o superblock=&lt;superblock number&gt;] [-o blocksize=&lt;block size&gt;] device    Option details:        -b: Display reserved bad blocks in the filesystem.        -f: Force execution.        -g: Briefly display the block group descriptor list (e.g., 63:1032192:-1:-1:786447:786463:790304).        -h: Only display superblock information without showing any block group descriptor details.        -i: Display filesystem information obtained from e2image, using the device as the path name of the image file.        -x: Display filesystem information in hexadecimal        -V: Display command version information and exit        -o superblock=superblock: Use the specified size superblock when checking the filesystem.            'This option is usually not needed unless the filesystem wizard is checking the remaining parts of a severely damaged filesystem.'        -o blocksize=blocksize: Specify block size when checking the filesystem.            'This option is usually not needed unless the filesystem wizard is checking the remaining parts of a severely damaged filesystem.'    Device parameter:        Specify the device where the information to be displayed is located.        Example:    dumpe2fs  /dev/sda2        Inode count:              1310720   Number of inode numbers in the filesystem        Block count:              5242112   Total number of block blocks in the filesystem        Reserved block count:     262105    Number of reserved block blocks        Free blocks:              2735814   Number of free block blocks        Free inodes:              1144046   Number of free inode numbers        First block:              0         First block number        Block size:               4096      Block size of 4KB        Fragment size:            4096      Fragment size        Reserved GDT blocks:      1024      Total number of reserved GDP blocks        Blocks per group:         32768     Number of block blocks per block group        Inodes per group:         8192      Number of inode numbers per block group        Inode blocks per group:   512       Number of block blocks occupied by inodes per block group        Flex block group size:    16        Size of the inode table        First inode:              11        The first inode number of the filesystem        Inode size:               256       Each inode size is 256 bytes        ..... omitted part        Group 159: (blocks 5210112-5242111) checksum 0xd815 [INODE_UNINIT, ITABLE_ZEROED]          Block bitmap is located at 4718607 (bg           inode bitmap is located at 4718623 (bg           inode table is located at 4726304-4726815 (bg           32000 available blocks, 8192 available inodes, 0 directories, 8192 unused inodes          Number of available blocks: 5210112-5242111          Number of available inodes: 1302529-1310720        Omitted...

(1): Basic Introduction

Linking storage devices (such as hard drives, partitions, network storage, etc.) with filesystems and mounting them to any root directory as a mount point allows the filesystem to access the data on the mounted storage device. In computers, storage devices are usually divided into multiple partitions or volumes. Each partition can contain an independent filesystem. However, these filesystems are not automatically available in the filesystem hierarchy and need to be mounted to be associated with a specific directory. Specifically, mounting involves the following concepts:

  • Storage Device: It can be a physical disk, partition, USB drive, network storage, etc. Each storage device has a unique device name, such as /dev/sda, /dev/sdb1, etc.

  • Filesystem: The way data is organized and managed on the storage device, such as ext4, NTFS, FAT32, etc. Each filesystem has its own characteristics and attributes.

  • Mount Point: The location of the filesystem in the filesystem hierarchy, which is also the target where the storage device is connected. It is an existing empty directory used to access files and folders on the storage device.

  • Mount Command: The command used to associate the storage device with the specified mount point. In Linux, the mount command is used to perform the mounting operation.

Through mounting, the directory structure and files of the filesystem can be accessed at the mount point and work in conjunction with other filesystems. For example, mounting a USB flash drive to the /mnt directory allows browsing and operating files in the flash drive through the /mnt directory. It is important to note that only users with sufficient permissions (usually root or using sudo) can perform mounting operations. Additionally, mounting is a temporary operation; after a system reboot, the device needs to be remounted unless it is added to the <span>/etc/fstab</span><span> file for automatic mounting.</span>

Before mounting, please note the following points:Before mounting, please note the following points:

  • A filesystem should not be mounted multiple times at different mount points (directories).

  • A single directory should not mount multiple filesystems.

  • The directory intended to be used as a mount point should theoretically be an empty directory.

Especially the last two points! If the directory at the mount point is not empty, then after mounting the filesystem, the original contents of the directory will temporarily disappear. For example, suppose your /home is originally in the same filesystem as the root directory (/), and there are originally /home/test and /home/vbird directories. Then you want to add a new disk and directly mount it under /home, when you mount the new partition, the /home directory will display the contents of the new partition, and the original test and vbird directories will temporarily be hidden,Note that it is hidden and not overwritten! Once the new partition is unmounted, the original contents of /home will reappear.

Common Steps for Disk Mounting:Common Steps for Disk Mounting:

  1. Confirm the disk or partition: Use tools like <span>lsblk</span><span> or </span><code><span>fdisk -l</span><span> to determine the device name of the disk or partition to be mounted; for example, /dev/sda, /dev/sdb1, etc.</span>

  2. Create a mount point: Choose an empty directory as the mount point. You can use the <span>mkdir</span><span> command to create a directory, such as mkdir /mnt/mydisk.</span>

  3. Perform the mount: Use the <span>mount</span><span> command to mount the disk or partition to the target directory (the device to be mounted must have a filesystem to be mounted).</span>

  4. Access disk content: You can now access the files and folders on the disk through the mount point path (here /mnt/mydisk).

  5. Automatic mounting: If you want the disk to be automatically mounted at each system startup, you can add the corresponding mount information to the /etc/fstab file.

  6. Perform unmounting: You can use the umount command to unmount the mounted disk or partition.

(2): Mounting Devices

Usage Specification:    mount [-lhV]    mount -a [options]    mount [options] [--source] &lt;source&gt; | [--target] &lt;mount point&gt;    mount [options] &lt;device&gt; &lt;mount point&gt;    mount &lt;operation&gt; &lt;mount point&gt; [&lt;target&gt;]Common Options:    -l: List currently mounted filesystems in the system without showing unmounted filesystems.    -h: View help documentation    -V: View version number    -a: Automatically mount all devices that support automatic mounting; (defined in the /etc/fstab file, and the mount options have the "automatic mount" feature)    -t: Specify the filesystem type on the device to be mounted;    -r: Mount the filesystem in read-only mode (same as -o ro)    -w: Mount the filesystem in read-write mode (default, same as -o rw)    -v: Print the current operation (e.g., during mounting: mount: /dev/vdb1 has been mounted to /mnt/game)    -n: Do not update /etc/mtab    -o: --options &lt;list&gt;: List of mount options, separated by commas;    &lt;device&gt;: Specify the device by path, such as /dev/sda5    &lt;file&gt;: Device file,    -L 'LABEL': Mount the device by label; for example -L 'MYDATA'    -U 'UUID': Mount the device by UUID; for example -U '0c50523c-xxx-a126711d406e'Additional: -o options that can be written in the list    sync: Synchronous mode;    async: Asynchronous mode (default);    atime/noatime: Update access time/do not update access time.            When accessing partition files, whether to update the access time of the file, the default is to update (if not updated, the file access and speed will be faster)    auto/noauto: Automatic mount/manual mount; whether to support automatic mounting (default automatic mount)            When executing mount -a command, whether to automatically install the contents of /etc/fstab    exec/noexec: Execute/not execute; set whether to allow executable files to be executed in the filesystem (default is exec allowed)    remount: Remount an already mounted filesystem, generally used to specify modified special permissions    rw/ro: Read-write/read-only, whether the filesystem is mounted with read-write permissions (default rw)    suid/nosuid: Has/does not have; set whether the filesystem has SUID and SGID special permissions (default is has)    user/nouser: Whether to allow ordinary users to mount this device    diratime/nodiratime: Directory access timestamp    dev/nodev: Whether to support using device files on this filesystem    usrquota: Write to indicate that the filesystem supports user disk quotas, default does not support    grpquota: Write to indicate that the filesystem supports group disk quotas, default does not support    acl: Enable acl functionality on this filesystem    defaults: Default, defaults will have many options: rw, suid, dev, exec, auto, nouser, and async
Device: Specify the device to be mounted;    (1) Device file: For example /dev/sda5    (2) Label: -L 'LABEL', for example -L 'MYDATA'    (3) UUID, -U 'UUID': For example -U '0c50523c-43f1-45e7-85c0-a126711d406e'    (4) Pseudo filesystem name: proc, sysfs, devtmpfs, configfsDirectory: Must exist in advance; it is recommended to use an empty directory; devices that are currently in use cannot be unmounted;

Basic Example:Basic Example:

Click Example 1: Mount the device /dev/vdb1 to the mount point /mnt/game
Preparation:    Create a partition and create a filesystem on the partition, here we created a filesystem for /dev/vdb1    Create a mount point, here we created an empty directory mount point using mkdir /mnt/gameExample method:    Mount /dev/vdb1 to /mnt/game; and set this device for read-only operation; print the current operation;    and set the filesystem type of the device; and set the -o option to not update the access time and synchronous mode; Mount command:    &gt;&gt; mount -vrt ext2 -o sync,noatime /dev/vdb1 /mnt/game        Print: mount: /dev/vdb1 has been mounted to /mnt/game.    Check the mount:        &gt;&gt; df -h            Filesystem        Size  Used  Available Used% Mount Point            tmpfs           341M  1.1M  339M    1% /run            /dev/vda2        59G  4.4G   53G    8% /            ....            /dev/vdb1      1007M   28K  956M    1% /mnt/game    Check if it is mounted read-only:        &gt;&gt; touch /mnt/game/abc.txt            touch: cannot touch '/mnt/game/abc.txt': Read-only filesystem'Additional: The most commonly used way'    &gt;&gt; mount -v /dev/vdb1 /mnt/game        This completes a basic mount (without any complicated parameters, at most one -v log)
Click Example 2: Use LABEL or UUID to mount the device to /mnt/videos
Preparation:    Create a partition and create a filesystem on the partition, here we created a filesystem for /dev/vdb2    Create a mount point, here we created an empty directory mount point using mkdir /mnt/videosMount command:    View the LABEL value of /dev/vdb2 (can be created when creating the filesystem):        &gt;&gt; blkid /dev/vdb*            Print: /dev/vdb2: LABEL="shebeiB" UUID="eaaxxx28e2" ...        &gt;&gt; mount -v -L shebeiB /mnt/videos            Print: mount: /dev/vdb2 has been mounted to /mnt/videos    Use UUID to mount the device:        &gt;&gt; mount -v -U eaab835f-073a-4b98-ba44-68c8e49228e2 /mnt/videos            Print: mount: /dev/vdb2 has been mounted to /mnt/videos

Mounted devices can be checked using <span>df -h</span> or <span>mount -l</span> to see if they are mounted

(3): Unmounting Devices

Directly unmount the mounted filesystem! After unmounting, you can use df or mount commands to see if it still exists in the directory tree.

Syntax:    umount [-hV]    umount -a [options]    umount [options] &lt;source&gt; | &lt;directory&gt;    Parameter Description:        -a: Automatically unmount all devices that support automatic mounting; (defined in the /etc/fstab file, and the mount options have the "automatic mount" feature)        -f: Force unmount! Can be used in cases where network filesystems (NFS) cannot be read        -n: Unmount without writing to update /etc/mtab        -l: Immediately disconnect the filesystem, clean up afterwards        -R: Recursively unmount the directory and its sub-objects        -r: If unmounting fails, try to remount in read-only mode        -t: Specify the filesystem collection        -v: Print the current operation        -h: View help documentation        -V: View version number
Note:    1: First check the already mounted filesystems; umount (unmount) can be followed by either the device or mount point;    2: Do not be in the directory to be unmounted when unmounting, otherwise it cannot be unmounted; if others are online, you can resolve it as follows:        'Error resolution: umount: /mnt/game: target is busy.'        Check the occupied directory and force unlock this directory (i.e., let the person occupying it go offline)        Suppose I have a /mnt/game that cannot be unmounted        &gt;&gt; fuser -cu /mnt/game            /mnt/game:   919540c(tom)           &gt;&gt; fuser -k /mnt/game            
Usage Example:        &gt;&gt; umount -f /dev/vdb1        &gt;&gt; umount /mnt/game

(4): Automatic Mounting Devices

Manually handling mount is not very user-friendly; we always need the system to automatically mount at boot! This way, we don’t have to mount every time we boot; therefore, this section will introduce the /etc/fstab file; we just need to modify the /etc/fstab file, but before starting, let’s talk about some system mounting restrictions:

  • The root directory (/) must be mounted and must be mounted before other mount points.

  • Other mount points must be any established directory, but must comply with the necessary system directory structure principles (FHS)

  • All mount points can only be mounted once at the same time.

  • All partitions can only be mounted once at the same time.

  • If unmounting, you must first move the working directory outside the mount point (and its subdirectories).

View the mount configuration file<span>cat /etc/fstab</span><span> content</span>

Specific options:    &lt;file system&gt;      &lt;mount point&gt;   &lt;type&gt;     &lt;options&gt;      &lt;dump&gt;  &lt;pass&gt;    '[Device, label, UUID, etc.]   [Mount point]   [Filesystem]  [Filesystem parameters]    [Dump]  [fsck]' Command query (see below mounted (/) directory is ext4):    root@VM-12-4-ubuntu:/mnt    ...            /dev/disk/by-uuid/7bccaefa-b039-4ff6-bd32-22dde0066c0b / ext4 defaults 0 1

In fact, /etc/fstab (filesystem table) is where we write all the options and parameters for mounting using the mount command. In addition, /etc/fstab also adds the dump option to support backup commands! There is also an fsck option to check whether to perform filesystem checks at boot; this file has six fields, detailed introduction as follows:

'First column: Disk device file name, UUID, LABEL name (&lt;file system&gt;)'    The data that can be filled in this field mainly has three types:        1: Device file name of the filesystem or disk; such as /dev/vda2, etc.        2: UUID name of the filesystem; such as UID=xxx        3: LABEL name of the filesystem; such as LABEL=xxx    Since each filesystem may have one of the three parameter values above, any of them can be used,    It is recommended to use UUID when modifying this configuration file, the specific UUID can be queried using blkid.'Second column: Mount point (mount point)'    This is any empty folder in the root directory, which needs to be mounted to this empty folder later.'Third column: Filesystem type within the disk partition (type)'    When manually mounting, it allows the system to automatically test the mount, so there is no need to write mount -t xxx;    But in this file, we must manually write the filesystem! As follows:        1: Ordinary device mount: ext2~4/xfs and other filesystem types        2: Swap partition swap: swap        3: Network mount address between Linux: nfs, Windows mount: cifs        4: CD iso9660, file cifs'Fourth column: Filesystem parameters (options)'    In fact, options have been mentioned once in the above mount, where we used mount -o xx,xx to specify, here I will summarize again:    1: async/sync (asynchronous/synchronous)        Set whether the disk operates in asynchronous mode, default is async (recommended)    2: auto/noauto (automatic mount/non-automatic mount)        When executing mount -a, whether this filesystem will be actively tested for mounting. Default is auto.    3: rw/ro (read-write/read-only)        Allow this partition to be mounted in read-write or read-only mode; if the data to be shared is not to be changed by users,        it can be set to read-only (ro). At this time, no user can modify the data of the mounted device; (default rw)    4: exec/noexec (executable/non-executable)        Restrict whether executable files can be executed in this mounted filesystem; if it is purely for storing data,        it can be set to noexec for better security.    5: user/nouser (allow/not allow user to mount)        Indicates whether to allow users to use the mount command to mount; generally, we do not want ordinary users to use mount,        as it is too unsafe, so this should be set to nouser.    6: suid/nosuid (has/does not have suid permission)      Whether the filesystem allows the existence of SUID; if it is not a directory for executable files, it can also be set to nosuid to cancel this function.    7: defaults        If it is defaults, it will have many options: rw, suid, dev, exec, auto, nouser, async, etc.'Fifth column: Whether it can be backed up by the dump command (dump)'    Dump is a command used for backup, but there are now too many backup solutions, generally ignore it, just enter 0; default is 0'Sixth column: Whether to check the sectors with fsck (pass)'    In the early boot process, there will be a period of time to check the local filesystem to see if the filesystem is complete (clean). However, this method is mainly used through fsck. The xfs filesystem we are using now cannot apply this, as xfs will check itself, so just fill in 0.

Basic Example:Basic Example:

Preparation:    Now there are three devices /dev/vdb1, /dev/vdb2, /dev/vdb3 to be configured in the /etc/fstab file; Configuration description:    /dev/vdb1 uses device path to mount, mounted to /mnt/game, and set to automatic mount, and read-only operation;    /dev/vdb2 uses LABEL method to mount, mounted to /mnt/videos, and set to automatic mount, and read-write operation;    /dev/vdb3 uses UID method to mount, mounted to /mnt/music, and set to not automatically mount, and read-write operation; Start working:    # Check if it is mounted (found it is not)    &gt;&gt; df -h        Filesystem        Size  Used  Available Used% Mount Point        /dev/vda2        59G  4.5G   52G    8% /        ...        tmpfs           340M  4.0K  340M    1% /run/user/0    # View specific partition slot information (that is, disk partition and installed filesystem)    &gt;&gt; blkid /dev/vdb*    # Modify the configuration file (/etc/fstab)    &gt;&gt; vim /etc/fstab        /dev/vdb1    /mnt/game    ext2    auto,ro    0    0        LABEL=shebeiB    /mnt/videos    ext3    auto,rw    0    0        UUID=a14f72f0-d450-473a-aaa2-4f2b811b0500  /mnt/music  ext4  noauto,rw  0  0    '# Important Note:'        After configuring as above, be sure to confirm that these devices have been unmounted;        Also, the above configuration must be checked, as errors may cause the system to fail to start normally.    # Automatic mounting (will automatically mount the auto-configured devices)        &gt;&gt; mount -a        &gt;&gt;  df -h            Filesystem        Size  Used  Available Used% Mount Point            tmpfs           341M  1.1M  339M    1% /run            /dev/vda2        59G  4.5G   52G    8% /            ...            tmpfs           340M  4.0K  340M    1% /run/user/0            /dev/vdb1      1007M   32K  956M    1% /mnt/game            /dev/vdb2       2.0G   92K  1.9G    1% /mnt/videos        # Among them, vdb3 is not auto, so it is not mounted    # Unmount the device and restart to see if it is mounted (the following test is that after booting, except for vdb3, the others are automatically mounted)        &gt;&gt; umount /dev/vdb1        &gt;&gt; umount /dev/vdb2

Practical Linux Disk Management (Partitioning, Formatting, Mounting)

(5): Other Special Device Mounting

We have discussed the common ext type filesystem mounting, but how to mount some special devices?

1: ISO Image Mounting

Preparation:    Prepare a .iso file and a mount point directory /mnt/guazai1, then start: Start mounting the ISO:    &gt;&gt; mount -vo loop /mnt/geodetic_coordinates.iso  /mnt/guazai1        Print: mount: /dev/loop12 has been mounted to /mnt/guazai1.    &gt;&gt; df -h        Filesystem        Size  Used  Available Used% Mount Point        tmpfs           388M  1.9M  386M    1% /run        /dev/sda2        20G   11G  8.5G   55% /        ...        /dev/loop12     135M  135M     0  100% /mnt/guazai1        &gt;&gt; ls -l /mnt/guazai1        Total 136741        -r-xr-xr-x 1 root root  1743984  8月 10 12:00  FangQian_4326.smwu        -r-xr-xr-x 1 root root  1744016  8月 10 12:00  FQ_2000.smwu        ...Unmount the ISO and check:    &gt;&gt; umount -f /dev/loop12    &gt;&gt; df -h        Filesystem        Size  Used  Available Used% Mount Point        tmpfs           388M  1.9M  386M    1% /run        /dev/sda2        20G   11G  8.5G   55% /        tmpfs           1.9G     0  1.9G    0% /dev/shm        tmpfs           5.0M  8.0K  5.0M    1% /run/lock        tmpfs           388M   64K  387M    1% /run/user/123        tmpfs           388M   48K  387M    1% /run/user/0

2: Mounting Windows Shared Files

First, we need to expose a shared file on Windows, and then ensure that the network between Windows and Linux is smooth.

Basic Introduction:    mount -t cifs is a Linux command used to mount directories shared based on the CIFS/SMB protocol.    CIFS (Common Internet File System) is a file sharing protocol used in Windows operating systems,    SMB (Server Message Block) is its predecessor, and both are basically the same. Once the environment is ready, start:    Windows IP: 192.168.0.144    Windows shared folder: //192.168.0.144/images    Username for Windows share = JavaScript; User password = 54088    We want to mount this shared file to /mnt/guazai2 (create: mkdir /mnt/guazai2) Mount the Windows shared file to Linux:    # The filesystem type used is cifs    mount -t cifs -o username=JavaScript,password=54088 //192.168.0.144/images /mnt/guazai2    # View mount information and unmount Windows shared file        &gt;&gt; df -h            Filesystem                Size  Used  Available Used% Mount Point            tmpfs                   388M  1.9M  386M    1% /run            /dev/sda2                20G   10G  8.6G   54% /            ...            //192.168.0.144/images  201G  3.5G  197G    2% /mnt/guazai2        &gt;&gt; umount  //192.168.0.144/images

Final Note:Final Note: (Author on Juejin: Ant Brother)  By now, we have basically mastered the knowledge of partitioning, formatting, and mounting; according to the parameters listed in the text, a lot of practice is needed to cope with some basic disk management techniques.

Practical Linux Disk Management (Partitioning, Formatting, Mounting)

Leave a Comment