FIELD NOTES / UNIX & LINUXNew tools on weekdays. Beyond the man page.
$dd

dd: move bytes without lying to yourself

Control block units, short reads, overwrite policy, and verification so a successful copy answers the question you actually asked.

THE DEEP DIVE16 MIN READ
01

Start with a stream copier

dd is often introduced with a disk-cloning one-liner. That skips the decisions that make the command safe: what one input block means, when a short read counts, whether the destination is truncated, and what a successful exit can actually prove. This article builds those decisions with regular files in a disposable lab. By the end, you will be able to select an exact region, choose an overwrite policy, recognize a partial transfer, and separate byte equality from provenance—the artifact's origin and handling history—and durability.

dd reads an input stream, groups what it reads into input blocks, optionally converts those blocks, and writes an output stream. It is a standalone utility, not a shell built-in. Reach for it when block boundaries, offsets, counts, or conversions are part of the copying contract. For an ordinary whole-file copy, cp usually states the intent more clearly.

These examples use GNU Coreutils dd 9.4 and Bash 5.2.21 on Linux. POSIX.1-2024 specifies dd's core operand grammar and conversions; GNU-only operands and flags are identified where they appear. Other implementations need their own documentation and tests.

Run the article in one Bash session and in order. The first block creates and enters a disposable dd-lab directory, creates a two-line input, copies it, and prints the copy. If dd-lab already exists, choose a different name and rerun the entire block; do not continue after failed setup. The shell's && operator runs the next command only after the previous one succeeds. Printf writes the two %s string arguments, adding the \n newline from its quoted format after each one. The printf deep dive explains that format-string model; the local rule needed here is that each %s consumes one following argument and \n ends its line. The > redirection creates or replaces source.txt before printf writes it.

The if=source.txt operand names the input file, and of=copy.txt names the output file. These are name=value operands parsed by dd, not shell assignments and not hyphen-prefixed flags. Without if=, dd reads standard input; without of=, it writes copied data to standard output. GNU status=none suppresses transfer statistics but not error diagnostics, making the fixed output readable. Without it, GNU dd also reports full and partial record counts and a timing-dependent transfer summary to standard error. Cat copies the finished file to the terminal only because dd succeeded.

TERMINALGNU COREUTILS AND BASH
export LC_ALL=C &&
mkdir dd-lab &&
cd dd-lab &&
printf '%s\n' alpha beta > source.txt &&
dd if=source.txt of=copy.txt status=none &&
cat copy.txt
TERMINALEXPECTED OUTPUT
alpha
beta

LC_ALL=C selects the C locale for this shell and its children, stabilizing the English diagnostics used later. The setting remains until changed or the shell ends. This fixture uses regular files only; no device path is involved.

02

Give every offset a unit

The next fixture contains 16 bytes. bs=4 tells GNU dd to read and write up to four bytes at a time. It also supplies the unit for skip= and count= here. skip=1 advances past one four-byte input block, and count=2 copies two input blocks. The destination is created or replaced.

TERMINALGNU COREUTILS AND BASH
printf '0123456789abcdef' > blocks.bin &&
dd if=blocks.bin of=middle.bin bs=4 skip=1 count=2 status=none &&
cat middle.bin
TERMINALEXPECTED OUTPUT
456789ab

The command skipped bytes 0 through 3 and copied bytes 4 through 11. By default, skip=N counts input blocks and seek=N counts output blocks; their byte sizes can differ when ibs= sets the input block size and obs= sets the output block size. GNU also accepts a B suffix on these numeric operands to request byte units. Never read skip=4096 as 4,096 bytes until you have identified its unit.

03

Read the record report, not just the file size

An input need not divide evenly into the chosen block size. This fixture has ten bytes. With bs=4, GNU reads two full four-byte records and one two-byte partial record. status=noxfer suppresses only the timing-dependent transfer line; it leaves the stable input and output record counts on standard error. The 2> redirection sends that diagnostic stream into records.txt, while copied bytes go to ten.copy. wc -c then counts bytes from its standard input, supplied by < ten.copy.

TERMINALGNU COREUTILS AND BASH
printf 'ABCDEFGHIJ' > ten.bin &&
dd if=ten.bin of=ten.copy bs=4 status=noxfer 2> records.txt &&
cat records.txt &&
wc -c < ten.copy
TERMINALEXPECTED OUTPUT ON GNU 9.4
2+1 records in
2+1 records out
10

The notation is full+partial, not successful+failed. A partial final record is normal at end of file. The wc deep dive explains the local check: wc -c reports how many bytes reached ten.copy; it does not prove where those bytes came from or whether ten was the intended amount.

04

A read can be short before end of stream

Regular files often satisfy a requested read until the final record, but pipes, devices, and other streams can return fewer bytes while more data may arrive later. GNU dd normally treats each successful read as one input block. Therefore, count=1 can stop after a short read.

This controlled producer writes AB, waits, then attempts to write CDEF. Braces group those commands as the left side of a pipeline. The pipe sends their standard output to dd; 2> keeps any producer diagnostic in short-source.err. bs=4 count=1 requests one read of up to four bytes. Immediately after the pipeline, Bash's PIPESTATUS array contains the status of the producer group at index 0 and dd at index 1. pipe_status=(...) copies both values before another command can replace them. The bracket test uses -ne 0 to ask whether the producer status is nonzero, setting a readable result. The second write meets a closed pipe, so the producer fails even though dd reports success.

Sleep 0.2 pauses the producer for one fifth of a second so the first short read is reproducible. Od -A n suppresses address labels, -t c displays byte values as characters, and -v prevents repeated rows from being abbreviated.

TERMINALGNU COREUTILS AND BASH
{ printf 'AB'; sleep 0.2; printf 'CDEF'; } 2> short-source.err |
  dd of=short.bin bs=4 count=1 status=none
pipe_status=("${PIPESTATUS[@]}")
if [ "${pipe_status[0]}" -ne 0 ]; then source_result=failed; else source_result=ok; fi
printf 'source result: %s; dd status: %s\n' "$source_result" "${pipe_status[1]}"
od -A n -t c -v short.bin
TERMINALEXPECTED OUTPUT ON GNU 9.4
source result: failed; dd status: 0
   A   B

The producer's failure is evidence that the pipeline as a whole did not satisfy the intended six-byte source contract. Looking only at dd's zero status would hide it. The diagnostic saved in short-source.err is from the synthetic producer's failed second write, not from dd.

05

Accumulate a complete input block when the contract requires it

iflag=fullblock changes the read side: it accumulates short reads until it fills an input block or reaches end of file. POSIX.1-2024 added fullblock; older standards do not specify it, and deployed implementations still need to be checked. The tested GNU 9.4 implementation supports it. Repeating the same controlled stream now lets the first two bytes and the next two bytes satisfy one four-byte block. The remaining EF bytes are outside count=1.

TERMINALGNU COREUTILS AND BASH
{ printf 'AB'; sleep 0.2; printf 'CDEF'; } 2> full-source.err |
  dd of=full.bin bs=4 count=1 iflag=fullblock status=none
pipe_status=("${PIPESTATUS[@]}")
if [ "${pipe_status[0]}" -ne 0 ]; then source_result=failed; else source_result=ok; fi
printf 'source result: %s; dd status: %s\n' "$source_result" "${pipe_status[1]}"
od -A n -t c -v full.bin
TERMINALEXPECTED OUTPUT ON GNU 9.4
source result: ok; dd status: 0
   A   B   C   D

fullblock does not promise that the source contains the expected total, and it cannot turn an I/O error into success. It only changes how short successful reads contribute to one input block. Check every producer separately when a pipeline constructs the source.

06

Select bytes without pretending they are blocks

GNU supplies iflag=skip_bytes,count_bytes when the requirement is an exact byte region. skip_bytes makes skip= count bytes, and count_bytes makes count= count bytes. Commas join multiple input flags in one iflag= operand. The fixture resembles a small image with a four-byte header, seven-byte payload, and four-byte trailer. The backslash at the end of the first dd display line is Bash line continuation: it removes the following newline so both physical lines form one command. Nothing, including a space, may follow that backslash.

TERMINALGNU COREUTILS AND BASH
printf 'HDR0payloadTAIL' > image.bin &&
dd if=image.bin of=payload.bin skip=4 count=7 \
  iflag=skip_bytes,count_bytes status=none &&
od -A n -t x1 -v payload.bin
TERMINALEXPECTED HEXADECIMAL BYTES
 70 61 79 6c 6f 61 64

The -t x1 display format asks od for one-byte hexadecimal units. Those bytes spell payload in ASCII. The od deep dive develops the distinction that matters here: dd selected bytes, while od chose a representation for displaying them. Neither command validates a file format. Without GNU's byte-counting flags, bs=1 skip=4 count=7 expresses byte units through a one-byte block size, usually with more read/write overhead.

07

Decide whether the destination is replaced or patched

seek=2 does not imply preserve everything else. With a nonzero seek, dd positions the output after two one-byte blocks and retains the existing prefix, but without conv=notrunc the resulting file ends after the data just written. The first copy therefore keeps ab, writes XYZ, and discards the old trailing bytes. The second command adds POSIX conv=notrunc, which prevents that truncation, so bytes outside the overwritten region remain. The additional creation policies discussed below are GNU-specific.

TERMINALGNU COREUTILS AND BASH
printf 'abcdefghij' > truncated.out &&
printf 'abcdefghij' > preserved.out &&
printf 'XYZ' > patch.bin &&
dd if=patch.bin of=truncated.out bs=1 seek=2 status=none &&
dd if=patch.bin of=preserved.out bs=1 seek=2 conv=notrunc status=none &&
printf '%s\n' 'default open:' &&
od -A n -t x1 -v truncated.out &&
printf '%s\n' 'with conv=notrunc:' &&
od -A n -t x1 -v preserved.out
TERMINALEXPECTED HEXADECIMAL BYTES
default open:
 61 62 58 59 5a
with conv=notrunc:
 61 62 58 59 5a 66 67 68 69 6a

notrunc is not a general safety switch: it authorizes in-place replacement and can leave stale trailing bytes. If the contract is create a new destination and fail if it exists, GNU conv=excl is clearer. If the contract is update only an existing destination, GNU conv=nocreat prevents creation but still permits overwriting. Select one policy deliberately and test it with disposable files.

08

Make an existing-file guard fail visibly

GNU conv=excl makes opening an existing output fail. Fixture creation is followed by &&, so the brace group runs only if guarded.out was freshly written; the braces group the expected-failure test and its inspection without starting another shell. This example uses Bash's if statement because dd failure is expected. The command after then would run only for status zero; that unexpected path prints a warning and exit 1 ends the current lab shell with failure. The else branch immediately saves $?, the previous command's status. The 2> redirection captures the diagnostic. status=none suppresses normal statistics, but it does not suppress the error. The final cat remains inside the guarded group, so it cannot make failed setup look successful.

TERMINALGNU COREUTILS AND BASH
printf '%s\n' original > guarded.out && {
  if dd if=patch.bin of=guarded.out conv=excl status=none 2> guard.err; then
    printf '%s\n' 'copy unexpectedly succeeded'
    exit 1
  else
    status=$?
    printf 'copy status: %s\n' "$status"
    cat guard.err
  fi
  cat guarded.out
}
TERMINALEXPECTED OUTPUT ON GNU 9.4
copy status: 1
dd: failed to open 'guarded.out': File exists
original

The original file is unchanged. A nonzero status says this copy failed; it does not guarantee that every failure leaves every destination untouched. Some errors occur after output has been opened or partially written. A consumer must discard or quarantine an incomplete destination unless the application's recovery contract says otherwise.

09

Separate completion, durability, and equality

A zero exit status means dd completed the operations it attempted. It does not by itself prove that the selected source was complete, that the destination is the intended device, or that storage will retain bytes through every failure. GNU conv=fsync asks dd to flush output data and metadata before it finishes. GNU also provides conv=fdatasync, which requests output-data flushing without the same metadata scope. These improve the completion contract; they do not establish provenance or make a live filesystem image consistent.

The command copies the synthetic image to a new regular file, requests the GNU fsync conversion, then hashes both files only after dd succeeds. sha256sum prints a SHA-256 digest and filename for each operand.

TERMINALGNU COREUTILS AND BASH
dd if=image.bin of=durable.copy conv=fsync status=none &&
sha256sum image.bin durable.copy
TERMINALEXPECTED OUTPUT
131c0780647588107146f70189d76bb866c6f43adf5e181013b4036534ae1861  image.bin
131c0780647588107146f70189d76bb866c6f43adf5e181013b4036534ae1861  durable.copy

Matching hashes are strong evidence that these two observed byte strings match. They do not prove who created the source, whether the source changed during acquisition, whether hidden bytes were outside the selected range, or whether either filename identifies the artifact you meant to handle. GNU status=progress can report periodic transfer counts on a long run, but its timing and rate are observational, not a correctness guarantee.

10

Treat raw access as a trust boundary

With sufficient permissions, dd can read or overwrite raw devices because such devices appear as byte streams. That is a legitimate administrative capability, not automatically a vulnerability in dd. It is also why a reversed if= and of=, a stale device name, a mounted destination, an unexpected short source, or an ignored write error can destroy data or produce misleading evidence.

For an authorized acquisition, work from a verified device identity, prefer a read-only path when the platform provides one, write to a new destination, record the expected size, preserve errors, and verify the result independently. The regular-file fixtures above model byte selection without normalizing a real-device command that readers might paste onto the wrong system. conv=noerror,sync is sometimes recommended for damaged media, but it changes error handling and may pad unreadable input blocks; it is not a universal recovery recipe and belongs in a workflow designed for the specific device and evidence requirements.

dd does not need a software flaw to become dangerous. If the invoking process has raw-device permission, an unsafe command can cross file-level boundaries or damage the device. Treat that as a capability and permission problem; reserve claims about a vulnerability or documented exploitation for cases backed by specific evidence.

Before a consequential run, state the source identity, destination identity, input and output units, exact expected byte count, overwrite policy, response to read and write errors, durability requirement, and independent verification method. Confirm which implementation supplies every extension. Keep the original artifact when provenance or repeatability matters. dd is dependable when the copy contract is explicit; the dangerous folklore begins when a successful command is allowed to stand in for questions it never answered.

Back to latest issue
HELP SHAPE THE NEXT ISSUE

What belongs in your toolbox?

Choose a command you want to know better. We start with familiar tools and work toward the less obvious ones.

READER’S CHOICE

What should we cover next?

Vote for a future deep dive, or suggest a command we missed.

One command name, up to 32 characters. Suggestions are reviewed by a person. A new article starts a fresh poll.

Loading poll…