我修改分区编号是为了看着舒服,磁盘没有 sda1 只有 sda2 就很想去改
本文示例将 /dev/sda2 改为 /dev/sda1

原始结构:

1
2
3
4
NAME   MAJ:MIN RM   SIZE RO TYPE MOUNTPOINTS
sda 8:0 0 465.8G 0 disk
└─sda2 8:1 0 465.6G 0 part /
sr0 11:0 1 1024M 0 rom

确认你拥有 root 权限

1
$ sudo su

关闭所有交换区,确保系统安全,同时尽可能的将目标磁盘上的所有分区解除挂载(否则更改需要重启后生效)

1
# swapoff -a

使用 sfdisk dump 分区表

1
# sfdisk -d /dev/sda > sda.bkp

复制新分区表

1
# cp sda.bkp sda.new

编辑新的分区表 sda.new

1
2
3
4
5
6
7
label: dos
label-id: 0x9ada1ada
device: /dev/sda
unit: sectors
sector-size: 512

/dev/sda2 : start= 421888, size= 976351232, type=83

可以直接修改下面的 sda2 到 sda1,修改完成后保存文件

将新分区表写入磁盘

1
# sfdisk /dev/sda < sda.new

如果你正在修改的磁盘是系统磁盘,或者启用了任何交换分区,使用下面的命令来强制写入:
这可能会破坏你的系统。风险自负。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# sfdisk --force /dev/sda < sda.new

Checking that no-one is using this disk right now ... FAILED

This disk is currently in use - repartitioning is probably a bad idea.
Umount all file systems, and swapoff all swap partitions on this disk.
Use the --no-reread flag to suppress this check.

Disk /dev/sda: 465.76 GiB, 500107862016 bytes, 976773168 sectors
Disk model: ST9500420AS
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: 0x9ada1ada

Old situation:

Device Boot Start End Sectors Size Id Type
/dev/sda2 421888 976773119 976351232 465.6G 83 Linux

>>> Script header accepted.
>>> Script header accepted.
>>> Script header accepted.
>>> Script header accepted.
>>> Script header accepted.
>>> Created a new DOS disklabel with disk identifier 0x9ada1ada.
/dev/sda1: Created a new partition 1 of type 'Linux' and of size 465.6 GiB.
Partition #1 contains a ext4 signature.
/dev/sda2: Done.

New situation:
Disklabel type: dos
Disk identifier: 0x9ada1ada

Device Boot Start End Sectors Size Id Type
/dev/sda1 421888 976773119 976351232 465.6G 83 Linux

The partition table has been altered.
Calling ioctl() to re-read partition table.
Re-reading the partition table failed.: Device or resource busy
The kernel still uses the old table. The new table will be used at the next reboot or after you run partprobe(8) or partx(8).
Syncing disks.

新的分区表重启后生效,此时应检查 /etc/fstab 是否有问题,确保重启后磁盘分区正常挂载。

重新安装 GRUB
仅针对传统 BIOS 引导的设备

1
2
# grub-install --target=i386-pc /dev/sda
# grub-mkconfig -o /boot/grub/grub.cfg

修改完成后新的结构:

1
2
3
4
NAME   MAJ:MIN RM   SIZE RO TYPE MOUNTPOINTS
sda 8:0 0 465.8G 0 disk
└─sda1 8:1 0 465.6G 0 part /
sr0 11:0 1 1024M 0 rom

完成上述操作后重启即可