dd

提供: ArchWiki
2022年10月7日 (金) 17:24時点におけるAshMyzk (トーク | 投稿記録)による版 (→‎ハードディスク全体の複製: 同期)
ナビゲーションに移動 検索に移動

関連記事

dd はファイルの変換とコピーを主な目的とする コアユーティリティ です。

cp と同様にデフォルトでは dd はファイルのビットごとのコピーを作成しますが、低レベルの I/O フロー制御機能を備えています。

詳細は、dd(1) またはフルドキュメントを参照してください。

ヒント: デフォルトでは、dd はタスクが完了するまで何も出力しません。操作の進行状況を監視するには、コマンドに status=progress オプションを追加します。
警告: この種のコマンドはどれも、データを不可逆的に破壊する可能性があるため、dd の使用には細心の注意を払う必要があります。

インストール

dd は GNU coreutils の一部です。このパッケージ内の他のユーティリティについては、Core utilities を参照してください。

ディスクの複製と復元

dd コマンドはシンプルでありながら多機能で強力なツールです。ファイルシステムの種類や OS に関係なく、コピー元からコピー先へブロック単位でコピーすることができます。ライブ CD のようなライブ環境から dd を使用するのが便利です。

警告: このタイプのコマンドと同様に使用時には十分な注意が必要です。さもないと、データが破壊される可能性があります。入力ファイル (if=) と出力ファイル (of=) の順番を覚えておいて、逆にしないでください。出力先のドライブやパーティション (of=) のサイズが、入力元 (if=) と同じかそれ以上である事を常に確認してください。

パーティションの複製

物理ディスク /dev/sda のパーティション 1 から、物理ディスク /dev/sdb のパーティション 1 へ:

# dd if=/dev/sda1 of=/dev/sdb1 bs=64K conv=noerror,sync status=progress
ノート: 出力パーティション of= (この例では sdb1) が存在しない場合、dd はこの名前のファイルを作成し、ルートファイルシステムをいっぱいにしてしまうので注意が必要です。

ハードディスク全体の複製

物理ディスク /dev/sda から物理ディスク /dev/sdb へ:

# dd if=/dev/sda of=/dev/sdb bs=64K conv=noerror,sync status=progress

このコマンドは、パーティションテーブル、ブートローダー、すべてのパーティション、UUID、データを含むドライブ全体を複製します。

  • bs= はブロックサイズを設定します。デフォルトは512バイトで、これは1980年代前半以降のハードドライブの「古典」的なブロックサイズですが、最も便利なものではありません。64KBや128KBなど、より大きな値を使用してください。また、「ブロックサイズ」だけでなく、読み取りエラーの伝搬にも影響を与えるため、下記の警告をお読みください。詳細は、[1][2] を参照して、最適な bs 値を見つけてください。
  • noerror はすべての読み取りエラーを無視して操作を続けるように dd に指示します。dd のデフォルトの動作は、いかなるエラーでも停止します。
  • sync は読み込みエラーがあった場合、入力ブロックをゼロで埋め、データのオフセットは同期されたままになります (読み込みエラーが疑われる場合、sync を用いた際の読み込みエラーの挙動に関する下記の詳細な説明を見てください)。
  • status=progress は、操作がいつ完了するかを推測するために使用できる転送統計を表示します。
ノート: 指定するブロックサイズは、読み取りエラーの処理方法に影響します。以下をお読みください。データの回復には、ddrescue を使用してください。

dd ユーティリティには、技術的には「入力ブロックサイズ」(IBS)と「出力ブロックサイズ」(OBS)があります。bs を設定すると、実質的に IBS と OBS の両方を設定することになります。通常、ブロックサイズが例えば 1MiB の場合、dd は 1024×1024 バイトを読み込み、同じバイト数を書き込みます。しかし、読み取りエラーが発生すると、事態はおかしくなります。多くの人は、noerror,sync オプションを使うと、dd が「読み込みエラーをゼロで埋める」と思っているようですが、そうではありません。ドキュメントによると、dd は読み込み完了後に OBS から IBS のサイズを埋める、つまりブロックの最後にゼロを追加するのです。つまり、ディスクの場合、512 バイトの読み取りエラーが読み取りの最初に1回発生しただけで、事実上 1MB 全体がめちゃくちゃになってしまうのです: 12ERROR89 は 120000089 ではなく 128900000 となります。

ディスクにエラーがないことが確認できれば、ブロックサイズを大きくしてコピーを進めることができ、コピーの速度が数倍向上します。例えば、Celeron 2.7GHz のシステムで、bs を 512 から 64K に変更すると、コピー速度が 35MB/s から 120MB/s になります。ただし、コピー元のディスクで発生した読み取りエラーは、コピー先のディスクではブロックエラーとして発生することに注意してください。つまり、512バイトのリードエラーは、出力先の 64 KiB ブロック全体をめちゃくちゃにします。

ヒント: dd の進行状況を表示するためには、status=progress オプションを使用してください。詳細については、dd(1) を参照してください。
ノート:
  • ext2/3/4 ファイルシステムの UUID を一意な状態に戻すには、すべてのパーティションで、tune2fs /dev/sdXY -U random を使用してください。スワップパーティションの場合は、代わりに、mkswap -U random /dev/sdXY を使ってください。
  • GPT ディスクを複製する場合、sgdisk を使うことで、ディスクとパーティションの GUID をランダム化し、GUID の一意性を保つことができます。
  • dd によるパーティションテーブルの変更はカーネルには登録されません。再起動せずに変更を通知するには、partprobe (GNU Parted の一部)のようなユーティリティを使ってください。

パーティションテーブルのバックアップ

fdisk#パーティションテーブルのバックアップとリストア または gdisk#パーティションテーブルのバックアップとリストア を参照。

Create disk image

Boot from a live medium and make sure no partitions are mounted from the source hard drive.

Then mount the external hard drive and backup the drive:

# dd if=/dev/sda conv=sync,noerror bs=64K | gzip -c  > /path/to/backup.img.gz

If necessary (e.g. when the resulting files will be stored on a FAT32 file system) split the disk image into multiple parts (see also split(1)):

# dd if=/dev/sda conv=sync,noerror bs=64K | gzip -c | split -a3 -b2G - /path/to/backup.img.gz

If there is not enough disk space locally, you may send the image through ssh:

# dd if=/dev/sda conv=sync,noerror bs=64K | gzip -c | ssh user@local dd of=backup.img.gz

Finally, save extra information about the drive geometry necessary in order to interpret the partition table stored within the image. The most important of which is the cylinder size.

# fdisk -l /dev/sda > /path/to/list_fdisk.info
ノート: You may wish to use a block size (bs=) that is equal to the amount of cache on the HD you are backing up. For example, bs=8192K works for an 8 MiB cache. The 64 KiB mentioned in this article is better than the default bs=512 bytes, but it will run faster with a larger bs=.
ヒント: gzip is only able to compress data using a single CPU core, which leads to a data throughput considerably lower than the write speeds on modern storage. In order to leverage multicore compression and create a disk image more quickly, one could for instance install the pigz package, and simply replace the gzip -c command above with pigz -c. For large disks, this can potentially save hours.

システムの復元

システムを復元するには:

# gunzip -c /path/to/backup.img.gz | dd of=/dev/sda

イメージが分割されている場合は、代わりに以下を使用してください:

# cat /path/to/backup.img.gz* | gunzip -c | dd of=/dev/sda

MBR のバックアップと復元

ディスクに変更を加える前に、ドライブのパーティションテーブルとパーティションスキームをバックアップしておくと良いでしょう。また、同じパーティションレイアウトを複数のドライブにコピーするためにバックアップを使うこともできます。

MBR はディスクの先頭 512 バイトに格納されています。MBR は4つの部分から成ります:

  1. 始めの 440 バイトにはブートストラップコード (ブートローダ) が含まれています。
  2. 次の 6 バイトにはディスクのシグネチャが含まれています。
  3. 次の 64 バイトにはパーティションテーブルが含まれています (各16バイトの4つのエントリ、各プライマリパーティションに1つのエントリ)。
  4. 最後の 2 バイトにはブートシグネチャが含まれています。

MBR を mbr_file.img として保存するには:

# dd if=/dev/sdX of=/path/to/mbr_file.img bs=512 count=1

完全な dd ディスクイメージから MBR を取り出すこともできます:

# dd if=/path/to/disk.img of=/path/to/mbr_file.img bs=512 count=1

バックアップから MBR を復元するには (注意。このコマンドは既存のパーティションテーブルを破壊し、ディスク上のすべてのデータにアクセスできなくなります):

# dd if=/path/to/mbr_file.img of=/dev/sdX bs=512 count=1
警告: 一致しないパーティションテーブルを使って MBR を復元すると、データを読み出せなくなり、ほぼ復元不可能になります。ブートローダを再インストールしたいだけならば、ブートローダは DOS 互換領域も実装しているので、そのブートローダの関連するページを見てください: GRUBSyslinux

ブートローダを復元したいだけで、プライマリパーティションテーブルのエントリに興味はないならば、単に MBR の先頭 440 バイトを復元すれば良いだけです:

# dd if=/path/to/mbr_file.img of=/dev/sdX bs=440 count=1

パーティションテーブルだけを復元するには、以下のコマンドを使う必要があります:

# dd if=/path/to/mbr_file.img of=/dev/sdX bs=1 skip=446 count=64

ブートローダーの削除

MBR ブートスラップコードを消去するには(別のオペレーティングシステムを完全に再インストールする必要がある場合に役立つ場合があります)、最初の440バイトのみをゼロにする必要があります:

# dd if=/dev/zero of=/dev/sdX bs=440 count=1

ディスク関連や他の使用場面

As some readers might already realized, the dd(1) core utility has an quite different command-line syntax compared to other utilities. Moreover, while supporting some unique features not found in other commodity utilities, several default behaviour (and sometimes, inability) it has is either less-ideal or potential error-prone if applied to specific scenario. For that reason, users may want to use some alternatives that better in some aspects in lieu of the dd core utility.

That said, it is still worth to note that since dd is a core utility, which is installed by default on Arch and many other systems, is preferable to some alternatives or more specialized utilities if it is inconvenient to install a new package on your system.

To cover the two aspects that addressed above, this section is dedicated to summarise the features of dd(1) core utility that rarely found in other commodity utilities, in a form that resemble pacman/Rosetta article but with quantities of examples being cut down to as few and simple as possible to just enough to examine these features of dd (as denoted by i.e. or To-clause in "Tip:" box under subsection), either in practice or pseudocode.

ノート: To keep this dedicated section in a reasonable length, comparison of alternative utilities only includes packages found in official repositories, in which case has obvious advantage over others being mentioned, and written in more details if necessary.
For more alternatives, see coreutils#dd alternatives.

バイナリファイルにブロック単位のパッチをインプレースに適用する

It is not an uncommon practice to use dd as a feature-limited binary file patcher in automated shell scripts since it is capable to seek the output file by given offset before writing, and to block-by-block (or byte-y-byte if bs=1) in-place patching the output file by adding the conv=notrunc option.

For example, to modify the timestamp part of first member in a cpio(5) § Portable ASCII Format archive, which starts at the 49th byte of the file (or with offset of 0x30 if you prefer hex notation):

$ touch a-randomly-chosen-file
$ bsdtar -cf example-modify-ts.cpio --format odc -- a-randomly-chosen-file
$ printf '%011o' "$(date -d "2019-12-21 00:00:00" +%s)" | dd conv=notrunc of=example-modify-ts.cpio seek=48 oflag=seek_bytes
ノート: The currently undocumented seek_bytes output flag is specified above for seeking the output in offset of bytes instead of blocks before starting to write(2) to output.
ヒント: To print byte stream from command-line input hex notation, use basenc(1) § base16 and/or printf(1).
ヒント: In this feature grid (i.e. write(2) with offset, with no truncation), instead of using dd, one may consider using a shell that supporting lseek(2) operation on shell-opened file descriptor if in case of:
  • the input file of dd is a pipe connected with a program that utilize splice(2) system call, and the user want to avoid unnecessary userspace I/O of dd for a better performance
  • or, to avoid frequently fork(2) in shell script loop to reduce performance penality
Then it would be necessary to let that shell open the file descriptor at first, and perform some seeking operation on the file descriptor to assign this file descriptor as output end of corresponding utility that use splice(2) system call (or a shell builtin command does not forking, as in following example of zshmodules(1) § sysseek):
$ zsh
$ local +xr openToWriteFD
$ zmodload zsh/system
$ sysopen -wo cloexec -u openToWriteFD example-modify-ts.cpio
$ sysseek -u $openToWriteFD 48
$ printf '%011o' "$(date -d "2019-12-21 00:00:00" +%s)" >&${openToWriteFD}
警告: Avoiding using this approach if you cannot ensure the program which you need it write with offset really utilize splice(2) (which implies that the program does not perform any kind of seeking or truncating on its output). Some programs may seek/truncate on input/output file descriptor by themselves even if this behaviour is unspecified on command line flags, which invalidates your shell's lseek(3) call, or unexpectedly truncates on opened file descriptor.

VFAT ファイルシステムイメージのボリュームラベルを表示する

ヒント: For this specific scenario, a more practical choice is file.

To read the filesystem volume label of an VFAT image file, which should be in total length of 11 bytes that padded by ASCII spaces, with an offset of 0x047:

$ truncate -s 33M empty-hole.img
$ fatlabel empty-hole.img LabelMe
$ dd iflag=skip_bytes,count_bytes count=11 skip=$((0x047)) if=empty-hole.img | sed -e 's% *$%%'
ノート: Both input flags are currently undocumented:
  • The former skip_bytes instruct dd to seek (or skip if input is not seekable) on input file by offset in quatity of byte instead of number of blocks before starting to read(2) from it.
  • The later count_bytes allow user to specifiy the total quantity of blocks to copy from input file in byte, instead of a number of blocks. It could be confusing since specifing this option could still subject to partial read(2), think it like a fractional value of input block count to better understand this behaviour.
ヒント: To transfer data from input (with an offset) to output within given length, in shell scripting, one may also consider curl(1) § r, as a commodity alternative that use range notation instead.
ノート: curl does not support seeking/skipping when input file is a device/pipe, another alternative socat(1) does support these operation on input file (incl. block device, excl. pipe and character device) but is less commodifying than curl:
$ socat -u -,seek=$((0x047)),readbytes=11 - < empty-hole.img | sed -e 's% *$%%'

パイプで繋がれたコマンド間で sponge する

ヒント: As already noted in title, a practical choice for this specific scenario is sponge(1), which supports atomic write by writing to ${TMPDIR:-/tmp} at first.

In following example, to avoid unnecessary long-lasting TCP connection on input end if the output end blocks longer than expected, one may put a dd between two commands with an output block size certainly larger than input while still reasonably smaller than available memory:

$ curl -qgsfL http://example.org/mirrors/ftp.archlinux.org/mirrored.md5deep | dd ibs=128k obs=200M | poor-mirroring-script-that-perform-mirroring-on-input-paths-line-by-line-wo-buffer-entire-list-first
警告: It should never be considered as a generic alternative to sponge(1) as dd truncates the output file before starting the entire copy operation.

サイズの制限付きでデータを転送する

It's a common practice to use dd in a data streaming shell script for limiting total length of data that a piped command may consume. For example, to inspect an ustar header block (tar(5) § POSIX ustar Archives) using a shell script function in a streaming manner:

ノート: The B suffix in argument to count option is a newerly introduced feature as of GNU coreutils v9.1 that has same effect of count_bytes input flag, is potentially confusable with option in forms like count=256k which indicate dd to copy 262144 input blocks instead of bytes.
hexdump-field() {
  set -o pipefail
  printf '%s[%d]:\n' $1 $2
  dd count=${2}B status=none | hexdump -e $2'/1 "%3.2x"' -e '" | " '$2'/1 "%_p" "\n"'
}

inspect-tar-header-block() {
  local -a hdrstack=(
    name 100
    mode 8
    uid 8
    gid 8
    size 12
    mtime 12
    checksum 8
    typeflag 1
    linkname 100
    magic 6
    version 2
    uname 32
    gname 32
    devmajor 8
    devminor 8
    prefix 155
    pad 12
  )
  set - ${hdrstack[@]}
  while test $# -gt 0; do
    hexdump-field $1 $2 || return
    shift 2
  done
}
$ bsdtar -cf - /dev/tty /dev/null 2>&- | dd count=1 skip=1 status=none | inspect-tar-header-block
ヒント: To streaming data from input to output within given length, an alternative is pv(1) § S, which supports splice(2) system call.
ノート: Another candidate alternative is head(1) § c, though implementation other than GNU coreutils and glibc may consume more data than requested, causing data misalignment issue in a streamingly shell script.
ヒント: In addition to above feature grid, if input file shall be lseek(2)'d by specific offset before streaming, and the output end of dd is a pipe connected with a program utilize splice(2), then, as an alternative, one may consider use: and pv(1) § S, (mentioned above) as in following bash example (assuming that file descriptor has not allocated in shell by ls -l /proc/self/fd in bash at first):
$ bash
$ exec 9<dummy-but-rather-large.img
$ xxd -g 0 -l 0 -s $((0x47ffff)) <&9
$ pv -qSs 104857601200 <&9 | program-that-process-load-of-data-but-does-not-limit-read-length-as-desired-nor-support-offset-read
$ exec 9<&-
ノート: Though incompatible with POSIX and some non-GNU implementation, it's feasible to replace the usage of xxd(1) § s in above example with dd in conjunction of count=0 and skip options as an example in coreutils test suite.

ブータブルなディスクイメージをブロックデバイスに書き込み、任意で進捗情報を表示する

See USB flash installation medium#Using_basic_command_line_utilities for examples of commodity utilities include the potential least adapted dd for that case.

ヒント: To write the content of a file to block device (with progress indicator), a suggested alternative is dd_rescue(1) § W. It is capable to avoid unnecessary writing in case of overwriting the old version of image on device with a newer version.

Troubleshooting

この記事あるいはセクションで使われている用語や表現には問題が存在します。
議論: The troubleshooting section currently only hold one subsection that describes the logic of dd's count option. Merge this into a previous section for a better overall reading experience in linear order. (議論: トーク:Dd#)

Partial read: copied data is smaller than requested

Files created with dd can end up with a smaller size than requested if a full input block is not available for various reasons (i.e. the underlying read(2) system call returns early.) This can happen when reading from a pipe(7), or when reading a device file like /dev/urandom and /dev/random (e.g. due to hardcoded limitation of underlying kernel device driver or insufficient entropy.), in conjunction of count=n option where n is the number of input block(s) to copy to output.

It is possible, but not guaranteed, that dd will warn you about such kind of issue:

dd: warning: partial read (X bytes); suggest iflag=fullblock

The solution is to do as the warning says, add iflag=fullblock option in addition to the input file option to the dd command. For example, to create a new file filled up with random data in total length of 40 megabytes:

$ dd if=/dev/urandom of=new-file-filled-by-urandom.bin bs=40M count=1 iflag=fullblock
ノート: When reading from a pipe or a special device file like we just mentioned below for copying a portion of file in a fixed length with count=n option being specified, it is suggested to, or always strongly recommended to add the iflag=fullblock option to the dd command if in case of wiping a portion of device or file.

When reading from a pipe, an alternative to iflag=fullblock is to limit bs to the PIPE_BUF constant value as defined in linux/limits.h to make the pipe(7) I/O atomic. For example, to prepare a text file filled up will random alphanumeric string in total length of 5 megabytes:

$ LC_ALL=C tr -dc '[:alnum:]' </dev/urandom | dd of=passtext-5m.txt bs=4k count=1280

Since the output file is not a pipe, one may prefer to use ibs and obs options to set block size separately for the (input) pipe and the (output) on-disk file. For example, to set a more efficient block size for output file:

$ LC_ALL=C tr -dc '[:alnum:]' </dev/urandom | dd of=passtext-5m.txt ibs=4k obs=64k count=1280
ヒント: In some circumstances, merely keep the the output block size the same the value as input block size with a value defined by PIPE_BUF constant may already be optimal.