0%

Linux dd命令

Linux 的 dd 命令

dd这个命令一直没有弄明白缩写的含义,这个命令应该归到Linux炫技里面,因为我也是很晚才用到,不过有些功能还可以尝试一下。

官方含义为:

dd - convert and copy a file

从官方含义来看,是不是定义为cc比较合适,^_^

dd命令用于复制文件,转换或者格式化文件。

dd命令功能很强大的,对于一些比较底层的问题,使用dd命令往往可以得到出人意料的效果。

命令格式

命令比较简单:

1
$ dd 选项

对于刚开始而言,仅仅下面几个掌握下面几个参数就完全够用了。

  • of=FILE, 将输出定位到FILE,而不是默认的stdout
  • bs=BYTES,每次读取的字节数,默认为512字节
  • count=N, 拷贝N个输入块
  • if=FILE, 从FILE输入,而不是默认的stdin

考虑替换cp命令

既然命令第一个说明就是拷贝文件,那么正常情况下基本是可以替换cp的,不过前提是有参数指定,比如:

1
2
3
4
5
6
7
8
9
10
11

# 默认cp拷贝,一个1GB的文件,花费1.05秒
$ time cp a b
cp a b 0.02s user 1.05s system 75% cpu 1.403 total

# 默认dd拷贝,一个1GB的文件,竟然花费了29.17秒
$ time dd if=a of=b
2048000+0 records in
2048000+0 records out
1048576000 bytes (1.0 GB, 1000 MiB) copied, 34.7214 s, 30.2 MB/s
dd if=a of=b 1.31s user 29.17s system 87% cpu 34.996 total

为什么dd这么慢,很简单,在不指定bs的情况下,默认为512字节,dd就会根据512来切分,时间都浪费在了这个上面。

所以简单地加上这个参数,迅速提升效率

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
$ time dd if=a of=b bs=2M
500+0 records in
500+0 records out
1048576000 bytes (1.0 GB, 1000 MiB) copied, 1.04747 s, 1.0 GB/s
dd if=a of=b bs=2M 0.00s user 1.05s system 78% cpu 1.332 total
$ time dd if=a of=b bs=4M
250+0 records in
250+0 records out
1048576000 bytes (1.0 GB, 1000 MiB) copied, 1.00866 s, 1.0 GB/s
dd if=a of=b bs=4M 0.00s user 1.00s system 76% cpu 1.304 total
$ time dd if=a of=b bs=8M
125+0 records in
125+0 records out
1048576000 bytes (1.0 GB, 1000 MiB) copied, 0.937974 s, 1.1 GB/s
dd if=a of=b bs=8M 0.00s user 0.92s system 79% cpu 1.164 total
$ time dd if=a of=b bs=10M
100+0 records in
100+0 records out
1048576000 bytes (1.0 GB, 1000 MiB) copied, 1.01666 s, 1.0 GB/s
dd if=a of=b bs=10M 0.00s user 1.03s system 82% cpu 1.257 total

测试硬盘速度

我最常使用的dd命令的用例是,测试硬盘的读写速度,比如很简单地写入1GB、10GB来看一下。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
$ dd if=/dev/zero of=tmp bs=1M count=1000
1000+0 records in
1000+0 records out
1048576000 bytes (1.0 GB, 1000 MiB) copied, 0.7338 s, 1.4 GB/s

$ dd if=/dev/zero of=tmp bs=2M count=500
500+0 records in
500+0 records out
1048576000 bytes (1.0 GB, 1000 MiB) copied, 0.611315 s, 1.7 GB/s

$ dd if=/dev/zero of=tmp bs=4M count=250
250+0 records in
250+0 records out
1048576000 bytes (1.0 GB, 1000 MiB) copied, 0.602517 s, 1.7 GB/s

然后根据这些参数,可以简单写一个脚本来评估系统的整体读写速率了。

当然dd系统管理员用的最多的应该是系统备份和克隆了,暂且不表。

处无为之事,行不言之教;作而弗始,生而弗有,为而弗恃,功成不居!

欢迎关注我的其它发布渠道