一、dd 命令核心基础
1. 核心语法
ddif=<输入源>of=<输出目标>[选项/参数]
2. 核心参数(高频使用)
|
|
|
|---|---|
bs=bytes |
|
count=blocks |
|
status=progress |
|
conv=关键字 |
noerror 出错不停止、fsync 强制落盘、ucase 转大写)
|
iflag/oflag |
direct 绕过缓存,测真实性能)
|
二、dd 命令典型应用场景(附解释)
1. 文件操作类
(1)基础文件复制(替代 cp,适合大文件)
ddif=/path/sourcefile of=/path/destfile bs=4M status=progress
(2)文本内容转换
# 小写转大写
ddif=testfile of=testfile_upper conv=ucase
# 大写转小写
ddif=testfile of=testfile_lower conv=lcase
2. 磁盘/分区操作类(核心高频)
(1)磁盘/分区备份(生成镜像文件)
# 备份 /dev/sda1 分区到镜像文件
ddif=/dev/sda1 of=/backup/sda1.img bs=4M status=progress conv=noerror,fsync
(2)镜像恢复到磁盘/分区
# 把镜像恢复到 /dev/sda1(⚠️ 目标分区会被覆盖,务必确认路径!)
ddif=/backup/sda1.img of=/dev/sda1 bs=4M status=progress conv=fsync
(3)制作启动盘(写入 ISO 到 U 盘)
# /dev/sdb 是 U 盘设备(不是分区!如 /dev/sdb1 错误)
ddif=ubuntu.iso of=/dev/sdb bs=4M status=progress conv=fsync
(4)备份/恢复分区表(精准操作)
# 备份分区表(MBR 分区表前 512 字节包含分区信息)
ddif=/dev/sda of=/backup/partition_table bs=512count=1status=progress
# 恢复分区表(⚠️ 风险极高,确保设备路径正确)
ddif=/backup/partition_table of=/dev/sda bs=512count=1status=progress
3. 性能测试类
(1)测试磁盘读取速度(绕过缓存)
# /dev/null 是空设备,不写入数据;iflag=direct 绕过系统缓存,测真实速度
ddif=/dev/sda of=/dev/null bs=1G count=1iflag=direct status=progress
(2)测试磁盘写入速度(绕过缓存)
# /dev/zero 生成空数据;oflag=direct 绕过缓存,测真实写入速度
ddif=/dev/zero of=/tmp/test_write bs=1G count=1oflag=direct status=progress
4. 数据擦除类(安全删除设备数据)
# 用随机数据覆盖整块磁盘(/dev/sda),无法恢复(耗时久)
ddif=/dev/urandom of=/dev/sda bs=1M status=progress
三、I/O 行为控制:iflag/oflag 扩展
|
|
|
|---|---|
direct |
|
sync |
|
append |
|
fullblock |
|
# 精准测试 4K 块大小的读取性能
ddif=/dev/sdb of=/dev/null bs=4K count=1000iflag=direct,fullblock status=progress
四、实战案例:swap 分区动态扩容
# 1. 创建 16G 的 swap 文件(fallocate 更快,dd 更兼容)
fallocate -l 16G /swapfile # 快速创建空文件
# 或用 dd(兼容性更好):dd if=/dev/zero of=/swapfile bs=1M count=16384 status=progress
# 2. 初始化 swap 文件(格式化)
mkswap /swapfile
# 3. 启用 swap 文件
swapon /swapfile
# 4. 设置永久生效(重启后仍生效)
echo"/swapfile none swap defaults 0 0">> /etc/fstab
# 5. 验证效果(查看 swap 大小)
free -h
总结
不想错过文章内容?读完请点一下“在看
”,加个“关注”,您的支持是我创作的动力
期待您的一键三连支持(点赞、在看、分享~)

