1. 程式人生 > 其它 >Linux 如何在映象檔案裡面建立分割槽

Linux 如何在映象檔案裡面建立分割槽

.
.
.
.
.
有的時候我們會通過dd命令來建立一個映象檔案,並且直接使用mkfs命令將其格式化。但如果映象檔案裡面並不直接是檔案系統,而是包含分割槽的,要怎麼才能使用裡面的分割槽呢?
接下來我們一步一步操作,建立一個映象檔案,對它進行分割槽、格式化,最後掛載使用。

  • 建立映象
>$ dd if=/dev/zero of=test.img bs=1024 count=8192
8192+0 records in
8192+0 records out
8388608 bytes (8.4 MB, 8.0 MiB) copied, 0.0114896 s, 730 MB/s

使用dd命令建立一個 8MB 的 test.img 映象檔案。

  • 對映象檔案進行分割槽
>$ fdisk test.img 

Welcome to fdisk (util-linux 2.37.4).
Changes will remain in memory only, until you decide to write them.
Be careful before using the write command.

Device does not contain a recognized partition table.
Created a new DOS disklabel with disk identifier 0x2caa228c.

Command (m for help): n
Partition type
   p   primary (0 primary, 0 extended, 4 free)
   e   extended (container for logical partitions)
Select (default p): 

Using default response p.
Partition number (1-4, default 1): 
First sector (2048-16383, default 2048): 
Last sector, +/-sectors or +/-size{K,M,G,T,P} (2048-16383, default 16383): 

Created a new partition 1 of type 'Linux' and of size 7 MiB.

Command (m for help): p
Disk test.img: 8 MiB, 8388608 bytes, 16384 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0x2caa228c

Device     Boot Start   End Sectors Size Id Type
test.img1        2048 16383   14336   7M 83 Linux

Command (m for help): w
The partition table has been altered.
Syncing disks.

使用fdisk命令在 test.img 檔案裡面建立一個主分割槽,使用了預設的 Linux 檔案系統格式。

  • 將映象檔案虛擬成塊裝置
>$ sudo losetup -f --show test.img 
/dev/loop0

test.img已經被虛擬為/dev/loop0裝置了。

  • 掛載虛擬檔案系統
>$ sudo kpartx -av /dev/loop0 
add map loop0p1 (253:0): 0 14336 linear 7:0 2048
>$ ls -l /dev/mapper/
total 0
crw-------. 1 root root 10, 236 Mar 16 09:50 control
lrwxrwxrwx. 1 root root       7 Mar 25 17:01 loop0p1 -> ../dm-0

使用kpartx命令將映象檔案虛擬為塊裝置,此時可以看到已經在/dev/mapper目錄下生成了test.img1分割槽對應的裝置檔案loop0p1

  • 格式化分割槽
$ sudo mkfs.ext4 /dev/mapper/loop0p1 
mke2fs 1.46.3 (27-Jul-2021)
Discarding device blocks: done                            
Creating filesystem with 7168 1k blocks and 1792 inodes

Allocating group tables: done                            
Writing inode tables: done                            
Creating journal (1024 blocks): done
Writing superblocks and filesystem accounting information: done
  • 掛載分割槽
>$ sudo mount /dev/mapper/loop0p1 /mnt
>$ mount -l | tail -n 1
/dev/mapper/loop0p1 on /mnt type ext4 (rw,relatime,seclabel)
>$ ls -la /mnt
total 17
drwxr-xr-x.  3 root root  1024 Mar 25 17:04 .
dr-xr-xr-x. 18 root root  4096 Nov 11 20:44 ..
drwx------.  2 root root 12288 Mar 25 17:04 lost+found

可以看到,分割槽已經成功掛載上了,並且可以使用了。
接下來我們將分割槽解除安裝掉。

  • 解除安裝裝置
# 解除安裝掛載點
>$ sudo umount /mnt
# 解除安裝分割槽
>$ sudo kpartx -d /dev/loop0
# 解除安裝虛擬塊裝置
>$ sudo losetup -d /dev/loop0