「Dd」の版間の差分

提供: ArchWiki
ナビゲーションに移動 検索に移動
(→‎Create disk image: 同期 & 翻訳)
(2人の利用者による、間の12版が非表示)
2行目: 2行目:
 
[[Category:コマンド]]
 
[[Category:コマンド]]
 
[[de:Dd]]
 
[[de:Dd]]
[[es:Dd]]
 
 
[[en:Dd]]
 
[[en:Dd]]
  +
[[es:Dd]]
 
[[pt:Dd]]
 
[[pt:Dd]]
  +
[[ru:Dd]]
 
{{Related articles start}}
 
{{Related articles start}}
 
{{Related|ディスクのクローン}}
 
{{Related|ディスクのクローン}}
{{Related|USB インストールメディア#dd を使う}}
+
{{Related|USB インストールメディア#基本的なコマンドラインユーティリティを使う}}
 
{{Related|ベンチマーク#dd}}
 
{{Related|ベンチマーク#dd}}
 
{{Related|ディスクの完全消去#dd}}
 
{{Related|ディスクの完全消去#dd}}
 
{{Related articles end}}
 
{{Related articles end}}
  +
[[Wikipedia:dd (Unix)|dd]] はファイルの変換とコピーを主な目的とする [[Core utilities|コアユーティリティ]] です。
 
  +
[[Wikipedia:ja:dd (Unix)|dd]] はファイルの変換とコピーを主な目的とする [[Core utilities|コアユーティリティ]] です。
   
 
''cp'' と同様にデフォルトでは ''dd'' はファイルのビットごとのコピーを作成しますが、低レベルの I/O フロー制御機能を備えています。
 
''cp'' と同様にデフォルトでは ''dd'' はファイルのビットごとのコピーを作成しますが、低レベルの I/O フロー制御機能を備えています。
23行目: 25行目:
 
== インストール ==
 
== インストール ==
   
''dd'' は GNU {{Pkg|coreutils}} の一部です。パッケージ内の他のユーティリティについては、[[Core utilities]] を参照してください。
+
''dd'' は GNU {{Pkg|coreutils}} の一部です。このパッケージ内の他のユーティリティについては、[[Core utilities]] を参照してください。
   
 
== ディスクの複製と復元 ==
 
== ディスクの複製と復元 ==
   
''dd'' コマンドはシンプルでありながら多機能で強力なツールです。ファイルシステムの種類や OS に関係なくコピー元からコピー先へブロック単位でコピーすることができます。ライブ CD のようなライブ環境から ''dd'' を使用するのが便利です。
+
''dd'' コマンドはシンプルでありながら多機能で強力なツールです。ファイルシステムの種類や OS に関係なくコピー元からコピー先へブロック単位でコピーすることができます。ライブ CD のようなライブ環境から ''dd'' を使用するのが便利です。
   
{{Warning|このタイプのコマンドと同様に使用時には十分な注意が必要です。データが破壊される可能性があります。入力ファイル ({{ic|1=if=}}) と出力ファイル ({{ic|1=of=}}) の順番を覚えておいて、逆にしないでください。出力先のドライブやパーティション ({{ic|1=of=}}) のサイズが、入力元 ({{ic|1=if=}}) と同じかそれ以上である事を常に確認してください。
+
{{Warning|このタイプのコマンドと同様に使用時には十分な注意が必要です。さもないと、データが破壊される可能性があります。入力ファイル ({{ic|1=if=}}) と出力ファイル ({{ic|1=of=}}) の順番を覚えておいて、逆にしないでください。出力先のドライブやパーティション ({{ic|1=of=}}) のサイズが、入力元 ({{ic|1=if=}}) と同じかそれ以上である事を常に確認してください。
 
}}
 
}}
   
38行目: 40行目:
 
# dd if=/dev/sda1 of=/dev/sdb1 bs=64K conv=noerror,sync status=progress
 
# dd if=/dev/sda1 of=/dev/sdb1 bs=64K conv=noerror,sync status=progress
   
{{Note|出力パーティション {{ic|1=of=}} (例では {{ic|sdb1}}) が存在しない場合、''dd'' はこの名前のファイルを作成し、ルートファイルシステムをいっぱいにしてしまうので注意が必要です。}}
+
{{Note|出力パーティション {{ic|1=of=}} (この例では {{ic|sdb1}}) が存在しない場合、''dd'' はこの名前のファイルを作成し、ルートファイルシステムをいっぱいにしてしまうので注意が必要です。}}
   
 
=== ハードディスク全体の複製 ===
 
=== ハードディスク全体の複製 ===
   
 
物理ディスク {{ic|/dev/sda}} から物理ディスク {{ic|/dev/sdb}} へ:
 
物理ディスク {{ic|/dev/sda}} から物理ディスク {{ic|/dev/sdb}} へ:
 
From physical disk {{ic|/dev/sda}} to physical disk {{ic|/dev/sdb}}:
 
   
 
# dd if=/dev/sda of=/dev/sdb bs=64K conv=noerror,sync status=progress
 
# dd if=/dev/sda of=/dev/sdb bs=64K conv=noerror,sync status=progress
   
MBR (つまりブートローダ)、すべてのパーティション、UUID、データを含むドライブ全体のクローン作成します。
+
このコマンドは、パーティションテーブル、ブートローダ、すべてのパーティション、UUID、データを含むドライブ全体を複製します。
   
* {{ic|1=bs=}} はブロックサイズを設定します。デフォルトは512バイトで、これは1980年代前半以降のハードドライブの「古典」的なブロックサイズですが、最も便利なものではありません。64KBや128KBなど、より大きな値を使用してください。また、「ブロックサイズ」だけでなく、読み取りエラーの伝搬にも影響を与えるため、下の警告をお読みください。詳細は、[https://www.mail-archive.com/eug-lug@efn.org/msg12073.html] と [http://blog.tdg5.com/tuning-dd-block-size/] を参照して、自分の使用例に最適な bs 値を見けてください。
+
* {{ic|1=bs=}} はブロックサイズを設定します。デフォルトは512バイトで、これは1980年代前半以降のハードドライブの「古典」的なブロックサイズですが、最も便利なものではありません。64KBや128KBなど、より大きな値を使用してください。また、「ブロックサイズ」だけでなく、読み取りエラーの伝搬にも影響を与えるため、下の警告をお読みください。詳細は、[https://www.mail-archive.com/eug-lug@efn.org/msg12073.html] と [http://blog.tdg5.com/tuning-dd-block-size/] を参照して、最適な bs 値を見けてください。
 
* {{ic|noerror}} はすべての読み取りエラーを無視して操作を続けるように ''dd'' に指示します。''dd'' のデフォルトの動作は、いかなるエラーでも停止します。
 
* {{ic|noerror}} はすべての読み取りエラーを無視して操作を続けるように ''dd'' に指示します。''dd'' のデフォルトの動作は、いかなるエラーでも停止します。
* {{ic|sync}} は読み込みエラーがあった場合、入力ブロックをゼロで埋め、データのオフセットは同期されたままになります。
+
* {{ic|sync}} は読み込みエラーがあった場合、入力ブロックをゼロで埋め、データのオフセットは同期されたままになります (読み込みエラーが疑われる場合、sync を用いた際の読み込みエラーの挙動に関する下記の詳細な説明を見てください)
 
* {{ic|1=status=progress}} は、操作がいつ完了するかを推測するために使用できる転送統計を表示します。
 
* {{ic|1=status=progress}} は、操作がいつ完了するかを推測するために使用できる転送統計を表示します。
   
{{Note|指定するブロックサイズは、読み取りエラーの処理方法に影響します。以下をお読みください。データの回復には、[[ディスクのクローン#ddrescue を使う|ddrescue]] を使います。}}
+
{{Note|指定するブロックサイズは、読み取りエラーの処理方法に影響します。以下をお読みください。データの回復には、[[ディスクのクローン#ddrescue を使う|ddrescue]] を使用してください。}}
   
''dd'' ユーティリティには、技術的に「入力ブロックサイズ」(IBS)と「出力ブロックサイズ」(OBS)があります。{{ic|bs}} を設定すると、実質的に IBS と OBS の両方を設定することになります。通常、ブロックサイズが例えば 1MiB の場合、dd は 1024×1024 バイトを読み込み、同じバイト数を書き込みます。しかし、読み取りエラーが発生すると、事態はおかしくなります。多くの人は、noerror,sync オプションを使うと、dd が「読み込みエラーをゼロで埋める」と思っているようですが、そうではありません。dd はドキュメントによると、読み込み完了後に OBS から IBS のサイズを埋める、つまりブロックの最後にゼロを追加するのです。つまり、ディスクの場合、512 バイトの読み取りエラーが読み取りの最初に1回発生しただけで、事実上 1MB 全体がめちゃくちゃになってしまうのです: 12ERROR89 は 120000089 ではなく 128900000 となります。
+
''dd'' ユーティリティには、技術的に「入力ブロックサイズ」(IBS)と「出力ブロックサイズ」(OBS)があります。{{ic|bs}} を設定すると、実質的に IBS と OBS の両方を設定することになります。通常、ブロックサイズが例えば 1MiB の場合、dd は 1024×1024 バイトを読み込み、同じバイト数を書き込みます。しかし、読み取りエラーが発生すると、事態はおかしくなります。多くの人は、{{ic|noerror,sync}} オプションを使うと、dd が「読み込みエラーをゼロで埋める」と思っているようですが、そうではありません。ドキュメントによると、dd は読み込み完了後に OBS から IBS のサイズを埋める、つまりブロックの最後にゼロを追加するのです。つまり、ディスクの場合、512 バイトの読み取りエラーが読み取りの最初に1回発生しただけで、事実上 1MB 全体がめちゃくちゃになってしまうのです: 12ERROR89 は 120000089 ではなく 128900000 となります。
   
ディスクにエラーがないことが確認できれば、ブロックサイズを大きくしてコピーを進めることができ、コピーの速度が数倍向上します。例えば、Celeron 2.7GHz のシステムで、bs を 512 から 64K に変更すると、コピー速度が 35MB/s から 120MB/s になります。ただし、コピー元のディスクで発生した読み取りエラーは、コピー先のディスクではブロックエラーとして発生することに注意してください。
+
ディスクにエラーがないことが確認できれば、ブロックサイズを大きくしてコピーを進めることができ、コピーの速度が数倍向上します。例えば、Celeron 2.7GHz のシステムで、bs を 512 から 64K に変更すると、コピー速度が 35MB/s から 120MB/s になります。ただし、コピー元のディスクで発生した読み取りエラーは、コピー先のディスクではブロックエラーとして発生することに注意してください。つまり、512バイトのリードエラーは、出力先の 64 KiB ブロック全体をめちゃくちゃにします
   
 
{{Tip|''dd'' の進行状況を表示するためには、{{ic|1=status=progress}} オプションを使用してください。詳細については、{{man|1|dd}} を参照してください。}}
 
{{Tip|''dd'' の進行状況を表示するためには、{{ic|1=status=progress}} オプションを使用してください。詳細については、{{man|1|dd}} を参照してください。}}
   
 
{{Note|
 
{{Note|
* ''ext2/3/4'' ファイルシステムの一意の UUID を取り戻すには、すべてのパーティションで、{{ic|tune2fs /dev/sd''XY'' -U random}} を使用します。スワップパーティションの場合は、代わりに、{{ic|mkswap /dev/sd''XY''}} を使ってください。
+
* ''ext2/3/4'' ファイルシステムの UUID を一意な状態に戻すには、すべてのパーティションで、{{ic|tune2fs /dev/sd''XY'' -U random}} を使用してください。スワップパーティションの場合は、代わりに、{{ic|mkswap -U random /dev/sd''XY''}} を使ってください。
  +
* [[GPT]] ディスクを複製する場合、[[GPT fdisk#パーティションテーブルのバックアップとリストア|sgdisk]] を使うことで、ディスクとパーティションの GUID をランダム化し、GUID の一意性を保つことができます。
 
* ''dd'' によるパーティションテーブルの変更はカーネルには登録されません。再起動せずに変更を通知するには、''partprobe'' ([[GNU Parted]] の一部)のようなユーティリティを使ってください。
 
* ''dd'' によるパーティションテーブルの変更はカーネルには登録されません。再起動せずに変更を通知するには、''partprobe'' ([[GNU Parted]] の一部)のようなユーティリティを使ってください。
 
}}
 
}}
   
  +
=== パーティションテーブルのバックアップ ===
=== Backing up the partition table ===
 
   
  +
[[fdisk#パーティションテーブルのバックアップとリストア]] または [[gdisk#パーティションテーブルのバックアップとリストア]] を参照。
See [[fdisk#Backup and restore partition table]] or [[gdisk#Backup and restore partition table]].
 
   
  +
=== ディスクイメージの作成 ===
=== 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''
 
# dd if=/dev/sda conv=sync,noerror bs=64K {{!}} gzip -c > ''/path/to/backup.img.gz''
   
  +
必要であれば (出力ファイルが [[FAT32]] ファイルシステム上に保存される場合など)、ディスクイメージを複数に分けてください ({{man|1|split}} も見てください):
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 {{man|1|split}}):
 
   
 
# dd if=/dev/sda conv=sync,noerror bs=64K {{!}} gzip -c {{!}} split -a3 -b2G - ''/path/to/backup.img.gz''
 
# dd if=/dev/sda conv=sync,noerror bs=64K {{!}} gzip -c {{!}} split -a3 -b2G - ''/path/to/backup.img.gz''
   
  +
ローカルに十分なディスクスペースがない場合、イメージを ''ssh'' を通して送ることもできます:
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
 
# 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''
 
# fdisk -l /dev/sda > ''/path/to/list_fdisk.info''
   
  +
{{Note|バックアップする HD のキャッシュの容量と同じブロックサイズ ({{ic|1=bs=}}) を使うと良いかもしれません。例えば、{{ic|1=bs=8192K}} は 8 MiB キャッシュでうまく行きます。この記事で説明されている 64 KiB は、デフォルトの {{ic|1=bs=512}} バイトよりも良いですが、より多くの {{ic|1=bs=}} を使えばより速く実行できます。}}
{{Note|You may wish to use a block size ({{ic|1=bs=}}) that is equal to the amount of cache on the HD you are backing up. For example, {{ic|1=bs=8192K}} works for an 8 MiB cache. The 64 KiB mentioned in this article is better than the default {{ic|1=bs=512}} bytes, but it will run faster with a larger {{ic|1=bs=}}.}}
 
   
  +
{{Tip|''gzip'' はデータ圧縮にシングルの CPU コアしか使用できません。そのせいで、データのスループットが最近のストレージの書き込みスピードよりかなり遅くなってしまいます。マルチコア圧縮でディスクイメージの作成をより速くするには、例えば {{Pkg|pigz}} などのパッケージをインストールし、上記の {{ic|gzip -c}} コマンドを {{ic|pigz -c}} に置き換えてください。巨大なディスクでは時間を節約できるかもしれません。また、他の圧縮アルゴリズム ({{Pkg|zstd}} など) を試しても良いかもしれません。
{{Tip|''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 {{Pkg|pigz}} package, and simply replace the {{ic|gzip -c}} command above with {{ic|pigz -c}}. For large disks, this can potentially save hours.}}
 
   
 
=== システムの復元 ===
 
=== システムの復元 ===
106行目: 107行目:
 
# cat ''/path/to/backup.img.gz*'' | gunzip -c | dd of=/dev/sda
 
# cat ''/path/to/backup.img.gz*'' | gunzip -c | dd of=/dev/sda
   
  +
== MBR のバックアップと復元 ==
== バイナリーファイルのパッチ適用 ==
 
   
  +
ディスクに変更を加える前に、ドライブのパーティションテーブルとパーティションスキームをバックアップしておくと良いでしょう。また、同じパーティションレイアウトを複数のドライブにコピーするためにバックアップを使うこともできます。
ファイルのオフセット {{ic|0x123AB}} を16進数列 {{ic|FF C0 14}} に置き換えたい場合は次のコマンドラインで実行できます: {{bc|1=# printf '\xff\xc0\x14' {{!}} dd seek=$((0x123AB)) conv=notrunc bs=1 of=''/path/to/file''}}
 
   
  +
MBR はディスクの先頭 512 バイトに格納されています。MBR は4つの部分から成ります:
== Backup and restore MBR ==
 
   
  +
# 始めの 440 バイトにはブートストラップコード (ブートローダ) が含まれています。
Before making changes to a disk, you may want to backup the partition table and partition scheme of the drive. You can also use a backup to copy the same partition layout to numerous drives.
 
  +
# 次の 6 バイトにはディスクのシグネチャが含まれています。
  +
# 次の 64 バイトにはパーティションテーブルが含まれています (各16バイトの4つのエントリ、各プライマリパーティションに1つのエントリ)。
  +
# 最後の 2 バイトにはブートシグネチャが含まれています。
   
  +
MBR を {{ic|mbr_file.img}} として保存するには:
The MBR is stored in the the first 512 bytes of the disk. It consists of 4 parts:
 
 
# The first 440 bytes contain the bootstrap code (boot loader).
 
# The next 6 bytes contain the disk signature.
 
# The next 64 bytes contain the partition table (4 entries of 16 bytes each, one entry for each primary partition).
 
# The last 2 bytes contain a boot signature.
 
 
To save the MBR as {{ic|mbr_file.img}}:
 
   
 
# dd if=/dev/sd''X'' of=''/path/to/mbr_file.img'' bs=512 count=1
 
# dd if=/dev/sd''X'' of=''/path/to/mbr_file.img'' bs=512 count=1
   
  +
完全な dd ディスクイメージから MBR を取り出すこともできます:
You can also extract the MBR from a full dd disk image:
 
   
 
# dd if=''/path/to/disk.img'' of=''/path/to/mbr_file.img'' bs=512 count=1
 
# dd if=''/path/to/disk.img'' of=''/path/to/mbr_file.img'' bs=512 count=1
   
  +
バックアップから MBR を復元するには (注意。このコマンドは既存のパーティションテーブルを破壊し、ディスク上のすべてのデータにアクセスできなくなります):
To restore (be careful, this destroys the existing partition table and with it access to all data on the disk):
 
   
 
# dd if=/''path/to/mbr_file.img'' of=/dev/sd''X'' bs=512 count=1
 
# dd if=/''path/to/mbr_file.img'' of=/dev/sd''X'' bs=512 count=1
   
  +
{{Warning|一致しないパーティションテーブルを使って MBR を復元すると、データを読み出せなくなり、ほぼ復元不可能になります。ブートローダを再インストールしたいだけならば、ブートローダは [https://www.pixelbeat.org/docs/disk/ DOS 互換領域]も実装しているので、そのブートローダの関連するページを見てください: [[GRUB]] や [[Syslinux]]。}}
{{Warning|Restoring the MBR with a mismatching partition table will make your data unreadable and nearly impossible to recover. If you simply need to reinstall the bootloader see their respective pages as they also employ the [https://www.pixelbeat.org/docs/disk/ DOS compatibility region]: [[GRUB]] or [[Syslinux]].}}
 
   
  +
ブートローダを復元したいだけで、プライマリパーティションテーブルのエントリに興味はないならば、単に MBR の先頭 440 バイトを復元すれば良いだけです:
If you only want to restore the boot loader, but not the primary partition table entries, just restore the first 440 bytes of the MBR:
 
   
 
# dd if=''/path/to/mbr_file.img'' of=/dev/sd''X'' bs=440 count=1
 
# dd if=''/path/to/mbr_file.img'' of=/dev/sd''X'' bs=440 count=1
   
  +
パーティションテーブルだけを復元するには、以下のコマンドを使う必要があります:
To restore only the partition table, one must use:
 
   
 
# dd if=''/path/to/mbr_file.img'' of=/dev/sd''X'' bs=1 skip=446 count=64
 
# dd if=''/path/to/mbr_file.img'' of=/dev/sd''X'' bs=1 skip=446 count=64
145行目: 142行目:
 
=== ブートローダーの削除 ===
 
=== ブートローダーの削除 ===
   
MBR ブートスラップコードを消去するには(別のオペレーティングシステムを完全に再インストールする必要がある場合に役立つ場合があります)、最初の440バイトのみをゼロにする必要があります
+
MBR ブートスラップコードを消去するには(別のオペレーティングシステムを完全に再インストールする必要がある場合に役立つ場合があります)、最初の440バイトのみをゼロにする必要があります:
   
 
# dd if=/dev/zero of=/dev/sd''X'' bs=440 count=1
 
# dd if=/dev/zero of=/dev/sd''X'' bs=440 count=1
   
  +
== ディスク関連や他の使用場面 ==
== Troubleshooting ==
 
   
  +
As some readers might already realized, the {{man|1|dd}} core utility has an [https://unix.stackexchange.com/a/12538#12538 quite different] command-line syntax compared to other utilities. Moreover, while supporting [https://unix.stackexchange.com/a/12538#12538 some unique features not found in other commodity utilities], several default behaviour (and sometimes, inability) it has is either [https://www.pixelbeat.org/docs/coreutils-gotchas.html#dd less-ideal] or [[dd#Partial_read:_copied_data_is_smaller_than_requested|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.
=== Partial read ===
 
   
  +
That said, it is still worth to note that since ''dd'' is a [[coreutils|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.
Files created with ''dd'' can end up with a smaller size than requested if a full input block is not available and the {{man|2|read}} system call returns early. This can happen when reading from a {{man|7|pipe}} or when reading from {{ic|/dev/random}} and there is not enough entropy[https://unix.stackexchange.com/a/121888], or from {{ic|/dev/urandom}} when reading more than 32 MiB[https://unix.stackexchange.com/a/178957].
 
   
  +
To cover the two aspects that addressed above, this section is dedicated to summarise the features of {{man|1|dd}} 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''.
It is possible, but not guaranteed, that ''dd'' will warn you about the issue:
 
  +
  +
{{note|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.<br>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 {{ic|seek}} the output file by given offset before writing, and to block-by-block (or byte-y-byte if {{ic|1=bs=1}}) in-place patching the output file by adding the {{ic|1=conv=notrunc}} option.
  +
  +
For example, to modify the timestamp part of first member in a {{man|5|cpio|Portable ASCII Format}} archive, which starts at the 49th byte of the file (or with offset of {{ic|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
  +
  +
{{note|The currently undocumented [https://github.com/coreutils/coreutils/commit/140eca15c4a3d3213629a048cc307fde0d094738 {{ic|seek_bytes}} output flag] is specified above for seeking the output in offset of bytes instead of blocks before starting to {{man|2|write}} to output.}}
  +
  +
{{tip|To print byte stream from command-line input hex notation, use {{man|1|basenc|base16}} and/or {{man|1|printf}}.}}
  +
  +
{{tip|In this feature grid (''i.e.'' {{man|2|write}} ''with offset, with'' no truncation), instead of using ''dd'', one may consider using a shell that supporting {{man|2|lseek}} operation on shell-opened file descriptor if in case of:
  +
  +
* the input file of ''dd'' is a pipe connected with a program that utilize {{man|2|splice}} system call, and the user want to avoid unnecessary userspace I/O of ''dd'' for a better performance
  +
* or, to avoid frequently {{man|2|fork}} 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 {{man|2|splice}} system call (or a shell builtin command does not forking, as in following example of {{man|1|zshmodules|sysseek}}):{{hc|$ zsh|<nowiki>$ 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}</nowiki>}}
  +
{{warning|Avoiding using this approach if you cannot ensure the program which you need it write with offset really utilize {{man|2|splice}} (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 {{man|3|lseek}} call, or unexpectedly truncates on opened file descriptor.}}}}
  +
  +
=== VFAT ファイルシステムイメージのボリュームラベルを表示する ===
  +
{{tip|For this specific scenario, a more practical choice is {{pkg|file}}.}}
  +
  +
To read the filesystem [https://wiki.osdev.org/FAT#FAT_32_2 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 {{ic|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% *$%%'
  +
{{note|[https://github.com/coreutils/coreutils/commit/140eca15c4a3d3213629a048cc307fde0d094738 Both input flags are currently undocumented]:
  +
* The former {{ic|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 {{man|2|read}} from it.
  +
* The later {{ic|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 {{man|2|read}}, think it like a fractional value of [[dd#Partial_read:_copied_data_is_smaller_than_requested|input block {{ic|count}}]] to better understand this behaviour.}}
  +
  +
{{tip|''To transfer data from input (with an offset) to output within given length'', in shell scripting, one may also consider {{man|1|curl|r,}} as a commodity alternative that use range notation instead.{{note|''curl'' does not support seeking/skipping when input file is a device/pipe, another alternative {{man|1|socat}} does support these operation on input file (incl. block device, ''excl. pipe and character device'') but is less commodifying than ''curl'':{{bc|<nowiki>$ socat -u -,seek=$((0x047)),readbytes=11 - < empty-hole.img | sed -e 's% *$%%'</nowiki>}}}}}}
  +
  +
=== パイプで繋がれたコマンド間で sponge する ===
  +
{{tip|As already noted in title, a practical choice for this specific scenario is {{man|1|sponge}}, which supports atomic write by writing to {{ic|<nowiki>${TMPDIR:-/tmp}</nowiki>}} 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 <nowiki>http://example.org/mirrors/ftp.archlinux.org/mirrored.md5deep</nowiki> | dd ibs=128k obs=200M | ''poor-mirroring-script-that-perform-mirroring-on-input-paths-line-by-line-wo-buffer-entire-list-first''
  +
  +
{{warning|It should never be considered as a generic alternative to {{man|1|sponge}} 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 ({{man|5|tar|POSIX ustar Archives}}) using a shell script function in a streaming manner:
  +
{{note|The {{ic|B}} suffix in argument to {{ic|count}} option is a [https://github.com/coreutils/coreutils/commit/97e9778296ead515e77a64942b84f88dcf36a176 newerly introduced] feature as of GNU coreutils v9.1 that has same effect of [[Dd#Printing_volume_label_of_a_VFAT_filesystem_image_(i.e._read_in_given_length,_with_offset)|{{ic|count_bytes}} input flag]], is potentially confusable with option in forms like {{ic|1=count=256k}} which indicate ''dd'' to copy 262144 input blocks instead of bytes.}}
  +
{{bc|<nowiki>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
  +
}</nowiki>}}
  +
$ bsdtar -cf - /dev/tty /dev/null 2>&- | dd count=1 skip=1 status=none | inspect-tar-header-block
  +
{{tip|''To streaming data from input to output within given length'', an alternative is {{man|1|pv|S,}} which supports {{man|2|splice}} system call.
  +
{{note|Another candidate alternative is {{man|1|head|c}}, though [[coreutils#Alternatives|implementation other than GNU coreutils]] and glibc [https://unix.stackexchange.com/a/12538#12538 may consume more data than requested], causing data misalignment issue in a streamingly shell script.}}}}
  +
{{Tip|In addition to above feature grid, if input file shall be {{man|2|lseek}}'d by specific offset before streaming, and the output end of ''dd'' is a pipe connected with a program utilize {{man|2|splice}}, then, as an alternative, one may consider use:
  +
* a shell with builtin seeking capability (''as already mentioned [[#Patching a binary file, block-by-block in-place|as alternative in a previous subsection]].'')
  +
* or, a Bourne-like shell (e.g. [[bash]]), with help of {{man|1|xxd|s}} for one-off {{man|2|lseek}} on shell-opened file descriptor,
  +
and {{man|1|pv|S,}} (''mentioned above'') as in following [[bash]] example (assuming that file descriptor has not allocated in shell by {{ic|ls -l /proc/self/fd}} in bash at first):{{hc|$ bash|<nowiki>$ exec 9<dummy-but-rather-large.img
  +
$ xxd -g 0 -l 0 -s $((0x47ffff)) <&9
  +
$ pv -qSs 104857601200 <&9 |</nowiki> ''program-that-process-load-of-data-but-does-not-limit-read-length-as-desired-nor-support-offset-read''
  +
$ exec 9<&-}}{{note|Though incompatible with POSIX and some non-GNU implementation, it's feasible to replace the usage of {{man|1|xxd|s}} in above example with ''dd'' in conjunction of {{ic|1=count=0}} and {{ic|skip}} options as [https://github.com/coreutils/coreutils/blob/4fd708810ce0e0d967c4c14e1ff2ff7b43440b58/tests/dd/skip-seek-past-file.sh#L74 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.
  +
{{tip|''To write the content of a file to block device (with progress indicator)'', a suggested alternative is {{man|1|dd_rescue|W}}. It is capable to avoid unnecessary writing in case of overwriting the old version of image on device with a newer version.}}
  +
  +
== Troubleshooting ==
  +
{{Style|The troubleshooting section currently only hold one subsection that describes the logic of dd's {{ic|count}} option. Merge this into a previous section for a better overall reading experience in linear order.}}
  +
=== 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 {{man|2|read}} system call returns early.) This can happen when reading from a {{man|7|pipe}}, or when reading a device file like {{ic|/dev/urandom}} and {{ic|/dev/random}} (e.g. due to [https://unix.stackexchange.com/a/178957#178957 hardcoded limitation of underlying kernel device driver] or insufficient entropy.), in conjunction of {{ic|1=count=''n''}} option where {{ic|''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
 
dd: warning: partial read (''X'' bytes); suggest iflag=fullblock
   
The solution is to do as the warning says and add {{ic|1=iflag=fullblock}} to the ''dd'' command. For example:
+
The solution is to do as the warning says, add {{ic|1=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
   
  +
{{Note|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 {{ic|1=count=''n''}} option being specified, it is suggested to, or always strongly recommended to add the {{ic|1=iflag=fullblock}} option to the ''dd'' command if in case of [[Securely wipe disk|wiping]] a [[#Remove bootloader|portion of device]] or [[Securely wipe disk/Tips and tricks#Wipe a single file|file]].}}
$ dd if=/dev/random of=bigsecret.img bs=1K count=1 iflag=fullblock
 
$ dd if=/dev/urandom of=bigsecret.img bs=40M count=1 iflag=fullblock
 
   
  +
When reading from a pipe, [https://unix.stackexchange.com/questions/556016/cat-dd-pipe-causes-partial-reads-without-iflag-fullblock-why-truncated-to-128 an alternative] to {{ic|1=iflag=fullblock}} is to limit {{ic|bs}} to the {{ic|PIPE_BUF}} constant value as defined in [https://elixir.bootlin.com/linux/latest/A/ident/PIPE_BUF {{ic|linux/limits.h}}] to make the {{man|7|pipe}} I/O atomic. For example, to prepare a text file filled up will random alphanumeric string in total length of 5 megabytes:
{{Note|It is strongly recommended to always add the {{ic|1=iflag=fullblock}} option to the ''dd'' command when the input file is {{ic|/dev/random}} or {{ic|/dev/urandom}}.}}
 
   
  +
$ LC_ALL=C tr -dc '[:alnum:]' </dev/urandom | dd of=passtext-5m.txt bs='''4k''' count=1280
An alternative for {{ic|/dev/urandom}} is to specify a block size smaller than 32 MiB, but a larger copy count. For example:
 
   
  +
Since the output file is not a pipe, one may prefer to use {{ic|1=ibs}} and {{ic|1=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:
$ dd if=/dev/urandom of=bigsecret.img bs=1M count=40
 
   
  +
$ LC_ALL=C tr -dc '[:alnum:]' </dev/urandom | dd of=passtext-5m.txt ibs=4k obs=''64k'' count=1280
When reading from a pipe, an alternative to {{ic|1=iflag=fullblock}} is to limit {{ic|bs}} to the {{ic|PIPE_BUF}} constant value, defined in {{ic|/usr/include/linux/limits.h}} [https://unix.stackexchange.com/questions/556016/cat-dd-pipe-causes-partial-reads-without-iflag-fullblock-why-truncated-to-128]. For example:
 
   
  +
{{tip|In some circumstances, merely keep the the output block size the same the value as input block size with a value defined by {{ic|PIPE_BUF}} constant may already be optimal.}}
$ cat input.img | dd of=output.img bs=4k count=100
 

2022年10月7日 (金) 17:41時点における版

関連記事

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#パーティションテーブルのバックアップとリストア を参照。

ディスクイメージの作成

ライブ環境のメディアから起動し、ソースのハードドライブのパーティションがマウントされていないことを確認してください。

次に、外部のハードドライブをマウントし、ドライブをバックアップしてください:

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

必要であれば (出力ファイルが FAT32 ファイルシステム上に保存される場合など)、ディスクイメージを複数に分けてください (split(1) も見てください):

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

ローカルに十分なディスクスペースがない場合、イメージを ssh を通して送ることもできます:

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

最後に、イメージに保存されているパーティションテーブルを解釈するために必要な、ドライブのジオメトリ情報に関する追加情報を保存します。最も重要なのはシリンダーサイズです。

# fdisk -l /dev/sda > /path/to/list_fdisk.info
ノート: バックアップする HD のキャッシュの容量と同じブロックサイズ (bs=) を使うと良いかもしれません。例えば、bs=8192K は 8 MiB キャッシュでうまく行きます。この記事で説明されている 64 KiB は、デフォルトの bs=512 バイトよりも良いですが、より多くの bs= を使えばより速く実行できます。

{{Tip|gzip はデータ圧縮にシングルの CPU コアしか使用できません。そのせいで、データのスループットが最近のストレージの書き込みスピードよりかなり遅くなってしまいます。マルチコア圧縮でディスクイメージの作成をより速くするには、例えば pigz などのパッケージをインストールし、上記の gzip -c コマンドを pigz -c に置き換えてください。巨大なディスクでは時間を節約できるかもしれません。また、他の圧縮アルゴリズム (zstd など) を試しても良いかもしれません。

システムの復元

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

# 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.