删除 DD 后的 linux swap 分区

按照平常的习惯,购买一个 vps 后都会去 dd 系统。在各种 dd 脚本中使用的最多的是萌咖的 dd 脚本。使用该脚本后会分出一个内存大小的空间作为 swap 分区。

可是有的 vps 本身的硬盘就不大,还分出一个内存大小的空间做 swap 分区,这时就应该删除 swap 分区,把空间添加至主分区上。

查看 swap 分区的位置

1
2
3
root@azure:~# swapon -s
Filename Type Size Used Priority
/dev/sdb5 partition 998396 7960 -2

关闭 swap

1
swapoff /dev/sdb5

删除开机自启动设置

1
2
# swap was on /dev/sda5 during installation
UUID=0bf87b3c-82e5-429c-8b58-f4b6fa447d3f none swap sw 0 0

重启并删除 swap 分区占用的硬盘容量

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
44
45
46
47
root@azure:~# fdisk -l
Disk /dev/sda: 64 GiB, 68719476736 bytes, 134217728 sectors
Disk model: Virtual Disk
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 4096 bytes
I/O size (minimum/optimal): 4096 bytes / 4096 bytes
Disklabel type: dos
Disk identifier: 0xe26f0c30

Device Boot Start End Sectors Size Id Type
/dev/sda1 * 2048 132216831 132214784 63G 83 Linux
/dev/sda2 132218878 134215679 1996802 975M 5 Extended
/dev/sda5 132218880 134215679 1996800 975M 82 Linux swap / Solaris

Partition 2 does not start on physical sector boundary.


Disk /dev/sdb: 4 GiB, 4294967296 bytes, 8388608 sectors
Disk model: Virtual Disk
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 4096 bytes
I/O size (minimum/optimal): 4096 bytes / 4096 bytes
Disklabel type: dos
Disk identifier: 0x8f57b3b1

Device Boot Start End Sectors Size Id Type
/dev/sdb1 2048 8386559 8384512 4G 83 Linux
root@azure:~# fdisk /dev/sda #根据自己的实际情况进行修改

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


Command (m for help): d #删除
Partition number (1,2,5, default 5): 5 #序号为5的分区

Partition 5 has been deleted.

Command (m for help): d #删除
Partition number (1,2, default 2): 2 #序号为2的分区

Partition 2 has been deleted.

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

将删除的空间添加至主空间

安装依赖

1
2
3
4
5
6
7
8
9
10
11
12
13
安装growpart软件

# Centos:
yum install -y cloud-utils-growpart
# Debian:
apt install -y cloud-guest-utils

* 如果你硬盘是GPT格式的请安装以下软件,MBR格式请忽略。

# Centos:
yum install gdisk -y
# Debian:
apt-get install gdisk -y

扩容

1
2
root@azure:~# growpart /dev/sda 1
CHANGED: partition=1 start=2048 old: size=132214784 end=132216832 new: size=134215647 end=134217695
1
2
3
4
5
root@azure:~# resize2fs /dev/sda1
resize2fs 1.46.2 (28-Feb-2021)
Filesystem at /dev/sda1 is mounted on /; on-line resizing required
old_desc_blocks = 8, new_desc_blocks = 8
The filesystem on /dev/sda1 is now 16776955 (4k) blocks long.

使用 df -h 查看是否扩容

1
2
3
4
5
6
7
8
root@azure:~# df -h
Filesystem Size Used Avail Use% Mounted on
udev 441M 0 441M 0% /dev
tmpfs 92M 500K 91M 1% /run
/dev/sda1 63G 2.3G 58G 4% /
tmpfs 457M 0 457M 0% /dev/shm
tmpfs 5.0M 0 5.0M 0% /run/lock
tmpfs 92M 0 92M 0% /run/user/0

如果 df -h 显示未成功扩容,则 reboot 重启后再次执行 resize2fs /dev/sda1