Skip to content

Latest commit

 

History

History
746 lines (571 loc) · 17.6 KB

dd.md

File metadata and controls

746 lines (571 loc) · 17.6 KB
title dd - Complete Disk Imaging and Data Manipulation Guide
description Complete guide to dd - Complete Disk Imaging and Data Manipulation Guide
category Storage
tags
storage
disk management
partitioning
difficulty beginner
last_updated 2026-06-06
related_commands

dd - Complete Disk Imaging and Data Manipulation Guide

Table of Contents

  1. dd Overview
  2. Basic Syntax and Options
  3. Disk Imaging
  4. Data Recovery
  5. Disk Wiping
  6. Partition Operations
  7. Performance Optimization
  8. Advanced Techniques
  9. Monitoring Progress
  10. Safety and Best Practices

dd Overview

What is dd?

dd (Data Description/Disk Dump) is a Unix/Linux command-line utility for low-level copying and converting of raw data. It operates at the block level, making it perfect for disk operations.

Key Features

- Disk-to-disk cloning
- Creating disk images
- Writing disk images
- Data recovery
- Secure disk wiping
- Partition backup/restore
- MBR/boot sector operations
- Raw data manipulation
- ISO creation

Common Use Cases

- Full disk backup/clone
- Creating bootable USB drives
- Disk benchmarking
- Data recovery from failing drives
- Secure data deletion
- Partition table backup
- Converting between formats
- Creating sparse files

Warning

dd is EXTREMELY POWERFUL and DANGEROUS
- No confirmation prompts
- Irreversible operations
- Wrong parameters = data loss
- ALWAYS double-check if= and of=
- Test with small files first
- Backup before using

Basic Syntax and Options

Command Structure

dd if=INPUT of=OUTPUT [OPTIONS]

# Required parameters:
if=FILE    # Input file (source)
of=FILE    # Output file (destination)

# Common options:
bs=BYTES   # Block size (read and write)
ibs=BYTES  # Input block size
obs=BYTES  # Output block size
count=N    # Copy only N input blocks
skip=N     # Skip N input blocks
seek=N     # Skip N output blocks
conv=KEYWORDS  # Conversion options
status=LEVEL   # Progress information level

Block Size (bs)

# Default: 512 bytes
dd if=/dev/sda of=/dev/sdb

# 1MB block size (faster for large transfers)
dd if=/dev/sda of=/dev/sdb bs=1M

# 4KB block size (matches most filesystem block size)
dd if=/dev/sda of=/dev/sdb bs=4K

# 64KB block size (good balance)
dd if=/dev/sda of=/dev/sdb bs=64K

# Separate input/output block sizes
dd if=/dev/sda of=/dev/sdb ibs=512 obs=4K

# Block size units:
# b=512, K=1024, M=1024K, G=1024M
# KB=1000, MB=1000KB, GB=1000MB

Count and Skip

# Copy first 100MB
dd if=/dev/sda of=/root/first-100mb.img bs=1M count=100

# Copy skipping first 100MB
dd if=/dev/sda of=/root/skip-100mb.img bs=1M skip=100

# Copy specific range (skip 100MB, copy 200MB)
dd if=/dev/sda of=/root/range.img bs=1M skip=100 count=200

# Seek (offset in output)
dd if=/dev/zero of=/tmp/sparse bs=1M seek=100 count=1
# Creates file with 100MB of zeros, then 1MB of data

Conversion Options (conv)

# Sync (pad blocks with zeros)
dd if=/dev/sda of=/dev/sdb conv=sync

# No error (continue on read errors)
dd if=/dev/sda of=/dev/sdb conv=noerror

# Combination (recommended for recovery)
dd if=/dev/sda of=/dev/sdb conv=sync,noerror

# Lowercase conversion
dd if=input.txt of=output.txt conv=lcase

# Uppercase conversion
dd if=input.txt of=output.txt conv=ucase

# ASCII to EBCDIC
dd if=input.txt of=output.txt conv=ebcdic

# Sparse file creation
dd if=/dev/sda of=image.img conv=sparse

# Full list of conv options:
# sync, noerror, notrunc, lcase, ucase
# block, unblock, swab, sync, excl
# nocreat, sparse, fdatasync, fsync

Disk Imaging

Complete Disk Clone

# Clone entire disk (disk-to-disk)
sudo dd if=/dev/sda of=/dev/sdb bs=64K status=progress

# Clone with error handling
sudo dd if=/dev/sda of=/dev/sdb bs=64K conv=sync,noerror status=progress

# Verification after clone
sudo cmp /dev/sda /dev/sdb

# Or with md5sum
sudo md5sum /dev/sda > /root/sda.md5
sudo md5sum /dev/sdb > /root/sdb.md5
diff /root/sda.md5 /root/sdb.md5

Create Disk Image File

# Create full disk image
sudo dd if=/dev/sda of=/backup/sda.img bs=64K status=progress

# Compressed image (on-the-fly compression)
sudo dd if=/dev/sda bs=64K status=progress | gzip > /backup/sda.img.gz

# Better compression with pigz (parallel gzip)
sudo dd if=/dev/sda bs=64K status=progress | pigz > /backup/sda.img.gz

# XZ compression (better ratio, slower)
sudo dd if=/dev/sda bs=64K status=progress | xz -9 > /backup/sda.img.xz

# With progress bar
sudo dd if=/dev/sda bs=64K | pv | gzip > /backup/sda.img.gz

Restore Disk Image

# Restore from image file
sudo dd if=/backup/sda.img of=/dev/sdb bs=64K status=progress

# Restore compressed image
gunzip -c /backup/sda.img.gz | sudo dd of=/dev/sdb bs=64K status=progress

# Or directly
sudo dd if=<(gunzip -c /backup/sda.img.gz) of=/dev/sdb bs=64K status=progress

# Restore XZ compressed
xz -dc /backup/sda.img.xz | sudo dd of=/dev/sdb bs=64K status=progress

Partition Image

# Backup single partition
sudo dd if=/dev/sda1 of=/backup/sda1.img bs=64K status=progress

# Restore partition
sudo dd if=/backup/sda1.img of=/dev/sdb1 bs=64K status=progress

# Backup partition table only (MBR)
sudo dd if=/dev/sda of=/backup/sda-mbr.img bs=512 count=1

# Backup first 1MB (MBR + space)
sudo dd if=/dev/sda of=/backup/sda-boot.img bs=1M count=1

# Restore MBR
sudo dd if=/backup/sda-mbr.img of=/dev/sda bs=512 count=1

ISO Image Creation

# Create ISO from CD/DVD
dd if=/dev/cdrom of=/backup/disk.iso bs=2048 status=progress

# Create ISO from directory (use genisoimage instead)
genisoimage -o output.iso -R -J /path/to/directory

# Write ISO to USB
sudo dd if=/path/to/image.iso of=/dev/sdb bs=4M status=progress
sudo sync

# Verify ISO written correctly
sudo dd if=/dev/sdb bs=4M count=$(stat -c%s /path/to/image.iso | awk '{print int($1/4194304)+1}') | md5sum
md5sum /path/to/image.iso

Data Recovery

Basic Recovery from Failing Disk

# Recover with error handling
sudo dd if=/dev/sda of=/backup/sda-recovery.img bs=64K conv=sync,noerror status=progress

# Options explained:
# conv=sync: Pad failed blocks with zeros
# conv=noerror: Continue on read errors
# status=progress: Show progress

# Better: use ddrescue instead of dd for recovery
# dd doesn't have retry logic or error mapping

Recover Specific Sectors

# Calculate sector offset
# sector_number × sector_size = byte_offset

# Read 10 sectors starting at sector 1000
sudo dd if=/dev/sda of=/root/sectors.dat bs=512 skip=1000 count=10

# Write sectors back
sudo dd if=/root/sectors.dat of=/dev/sda bs=512 seek=1000

MBR Recovery

# Backup MBR before operations
sudo dd if=/dev/sda of=/root/mbr-backup.img bs=512 count=1

# Restore MBR if corrupted
sudo dd if=/root/mbr-backup.img of=/dev/sda bs=512 count=1

# Clear MBR (dangerous!)
sudo dd if=/dev/zero of=/dev/sda bs=512 count=1

# Restore only boot code (preserve partition table)
sudo dd if=/root/mbr-backup.img of=/dev/sda bs=446 count=1

Boot Sector Backup

# Backup partition boot sector
sudo dd if=/dev/sda1 of=/root/sda1-boot.img bs=512 count=1

# Restore boot sector
sudo dd if=/root/sda1-boot.img of=/dev/sda1 bs=512 count=1

Disk Wiping

Simple Zero Wipe

# Wipe entire disk with zeros
sudo dd if=/dev/zero of=/dev/sdb bs=1M status=progress

# Wipe faster (larger blocks)
sudo dd if=/dev/zero of=/dev/sdb bs=4M status=progress

# Wipe partition
sudo dd if=/dev/zero of=/dev/sdb1 bs=1M status=progress

# Wipe first 100MB
sudo dd if=/dev/zero of=/dev/sdb bs=1M count=100

Random Data Wipe

# Single pass random data
sudo dd if=/dev/urandom of=/dev/sdb bs=1M status=progress

# Multiple pass wipe (DoD 5220.22-M)
#!/bin/bash
DISK=/dev/sdb

echo "Pass 1/3: Zeros"
sudo dd if=/dev/zero of=$DISK bs=1M status=progress

echo "Pass 2/3: Ones"
sudo dd if=/dev/zero of=$DISK bs=1M status=progress | tr '\000' '\377'

echo "Pass 3/3: Random"
sudo dd if=/dev/urandom of=$DISK bs=1M status=progress

sync

Fast Wipe (Beginning Only)

# Wipe first 100MB (makes recovery very difficult)
sudo dd if=/dev/urandom of=/dev/sdb bs=1M count=100

# Wipe last 100MB (partition table at end for GPT)
disk_size=$(blockdev --getsize64 /dev/sdb)
skip_blocks=$(( (disk_size - 104857600) / 1048576 ))
sudo dd if=/dev/urandom of=/dev/sdb bs=1M seek=$skip_blocks count=100

Secure Erase (Better Methods)

# For SSDs, use built-in secure erase instead
# hdparm method (see hdparm.md)
sudo hdparm --security-erase Pwd /dev/sdb

# Or use shred (better than dd for wiping)
sudo shred -vfz -n 3 /dev/sdb

# blkdiscard for SSDs (if supported)
sudo blkdiscard /dev/sdb

Partition Operations

Clone Partition to Different Size

# Source: 100GB partition
# Target: 200GB partition

# Clone partition
sudo dd if=/dev/sda1 of=/dev/sdb1 bs=64K status=progress

# Resize filesystem (ext4)
sudo e2fsck -f /dev/sdb1
sudo resize2fs /dev/sdb1

# For XFS
sudo xfs_growfs /mount/point

Sparse File Creation

# Create sparse file (10GB file, mostly empty)
dd if=/dev/zero of=/tmp/sparse.img bs=1 count=0 seek=10G

# Check actual disk usage
ls -lh /tmp/sparse.img        # Shows 10G
du -h /tmp/sparse.img         # Shows actual usage (much less)

# Create with some data
dd if=/dev/zero of=/tmp/sparse.img bs=1M seek=1000 count=100
# Creates 1GB of zeros, then 100MB of data

Partition Table Operations

# Backup partition table (MBR)
sudo dd if=/dev/sda of=/root/partition-table.img bs=512 count=1

# Backup GPT partition table
sudo dd if=/dev/sda of=/root/gpt-primary.img bs=512 count=34
sudo dd if=/dev/sda of=/root/gpt-secondary.img bs=512 skip=$(( $(blockdev --getsz /dev/sda) - 33 )) count=33

# Restore partition table
sudo dd if=/root/partition-table.img of=/dev/sdb bs=512 count=1
sudo partprobe /dev/sdb

Performance Optimization

Block Size Impact

# Test different block sizes
#!/bin/bash
TEST_FILE=/tmp/dd-test-$(date +%s)
SIZE=1G

for bs in 512 1K 4K 16K 64K 256K 1M 4M; do
    echo "Testing block size: $bs"

    # Write test
    write_time=$(time -p dd if=/dev/zero of=$TEST_FILE bs=$bs count=$((1073741824 / $(numfmt --from=iec $bs))) 2>&1 | grep real | awk '{print $2}')

    # Clear cache
    sync; echo 3 > /proc/sys/vm/drop_caches

    # Read test
    read_time=$(time -p dd if=$TEST_FILE of=/dev/null bs=$bs 2>&1 | grep real | awk '{print $2}')

    echo "  Write: ${write_time}s, Read: ${read_time}s"

    rm -f $TEST_FILE
done

# Typical results:
# Small bs (512-4K): Slower, more CPU overhead
# Medium bs (64K-256K): Good balance
# Large bs (1M-4M): Fastest for sequential, may waste cache

Direct I/O (iflag/oflag)

# Bypass cache (direct I/O)
sudo dd if=/dev/sda of=/backup/sda.img bs=1M iflag=direct oflag=direct status=progress

# Flags:
# iflag=direct: Direct I/O for input
# oflag=direct: Direct I/O for output
# iflag=sync: Synchronized I/O for input
# oflag=sync: Synchronized I/O for output
# iflag=fullblock: Accumulate full blocks (useful with pipes)

# Good for:
# - Disk benchmarking
# - Large file transfers
# - Avoiding cache pollution

# Bad for:
# - Small files
# - Multiple small operations

Parallel Processing

# Split large operation into parallel chunks
#!/bin/bash

DISK=/dev/sda
OUTPUT=/backup/sda.img
CHUNK_SIZE=10G  # 10GB chunks
DISK_SIZE=$(blockdev --getsize64 $DISK)

chunks=$(( DISK_SIZE / $(numfmt --from=iec $CHUNK_SIZE) + 1 ))

for i in $(seq 0 $((chunks - 1))); do
    skip=$((i * $(numfmt --from=iec $CHUNK_SIZE) / 1048576))  # In MB
    count=$(($(numfmt --from=iec $CHUNK_SIZE) / 1048576))

    dd if=$DISK of=${OUTPUT}.part${i} bs=1M skip=$skip count=$count status=progress &
done

wait

# Combine parts
cat ${OUTPUT}.part* > $OUTPUT
rm ${OUTPUT}.part*

Network Transfer Optimization

# Transfer over network with compression
# On source machine:
sudo dd if=/dev/sda bs=1M | gzip -1 | ssh user@destination "cat > /backup/sda.img.gz"

# On destination, receive and write:
ssh user@source "sudo dd if=/dev/sda bs=1M | gzip -1" | gunzip | sudo dd of=/dev/sdb bs=1M

# With pv for progress:
sudo dd if=/dev/sda bs=1M | pv | gzip -1 | ssh user@dest "cat > /backup/sda.img.gz"

# With mbuffer for buffering:
sudo dd if=/dev/sda bs=1M | mbuffer -m 1G | gzip | ssh user@dest "cat > /backup/sda.img.gz"

Advanced Techniques

Creating Bootable USB

# Write ISO to USB drive
sudo dd if=/path/to/linux.iso of=/dev/sdb bs=4M status=progress
sudo sync

# Verify write
sudo dd if=/dev/sdb bs=4M count=$(stat -c%s /path/to/linux.iso | awk '{print int($1/4194304)+1}') | md5sum
md5sum /path/to/linux.iso

# Ensure all data written
sudo sync
sudo eject /dev/sdb

Disk Benchmarking

# Write speed test
sudo dd if=/dev/zero of=/tmp/test bs=1M count=1024 oflag=direct
# Shows write speed

# Read speed test (clear cache first)
sync; echo 3 > /proc/sys/vm/drop_caches
sudo dd if=/tmp/test of=/dev/null bs=1M iflag=direct
# Shows read speed

# Full benchmark script
#!/bin/bash
echo "=== Disk Benchmark ==="

# Sequential write
echo "Sequential write (1GB):"
dd if=/dev/zero of=/tmp/bench bs=1M count=1024 conv=fdatasync 2>&1 | grep copied

# Sequential read
sync; echo 3 > /proc/sys/vm/drop_caches
echo "Sequential read (1GB):"
dd if=/tmp/bench of=/dev/null bs=1M 2>&1 | grep copied

# Random write (simulate)
echo "Random write (1GB):"
dd if=/dev/urandom of=/tmp/bench bs=4K count=262144 conv=fdatasync 2>&1 | grep copied

rm /tmp/bench

Convert and Transform Data

# Convert text case
dd if=input.txt of=output.txt conv=ucase  # Uppercase
dd if=input.txt of=output.txt conv=lcase  # Lowercase

# Swap byte order (16-bit words)
dd if=input.bin of=output.bin conv=swab

# Create file with specific pattern
# Create 1GB file of 'A' characters
tr '\0' 'A' < /dev/zero | dd of=/tmp/pattern.txt bs=1M count=1024 iflag=fullblock

# Create file with incrementing bytes
seq 0 255 | awk '{printf "%c", $1}' | dd of=/tmp/increment.bin bs=1 count=256

Rescue Deleted Files Area

# Backup area where file was deleted
# (for later recovery with tools like photorec)

# Find inode location
debugfs /dev/sda1
debugfs> stat filename

# Note block numbers, then:
sudo dd if=/dev/sda1 of=/root/recovery-area.img bs=4096 skip=START_BLOCK count=NUM_BLOCKS

Monitoring Progress

Built-in Status

# Show progress (modern dd)
dd if=/dev/sda of=/dev/sdb bs=1M status=progress

# Output:
# 1234567890 bytes (1.2 GB, 1.1 GiB) copied, 45 s, 27.4 MB/s

# Send USR1 signal to running dd (old method)
# In another terminal:
while true; do
    killall -USR1 dd
    sleep 5
done

Using pv (Pipe Viewer)

# Install pv
sudo apt-get install pv

# With pv (shows progress bar)
sudo dd if=/dev/sda bs=1M | pv -s 1T | dd of=/dev/sdb bs=1M

# Or:
pv /dev/sda | sudo dd of=/dev/sdb bs=1M

# With size specification
pv -s $(blockdev --getsize64 /dev/sda) /dev/sda | sudo dd of=/dev/sdb bs=1M

# pv shows:
# - Progress bar
# - Percentage
# - Transfer rate
# - ETA

Progress Script

#!/bin/bash
# Monitor dd progress

DD_PID=$(pgrep -x dd)

if [ -z "$DD_PID" ]; then
    echo "No dd process running"
    exit 1
fi

echo "Monitoring dd (PID: $DD_PID)"

while kill -0 $DD_PID 2>/dev/null; do
    killall -USR1 dd
    sleep 5
done

echo "dd completed"

Safety and Best Practices

Pre-flight Checks

#!/bin/bash
# Safety check before dd

SOURCE=$1
DEST=$2

echo "=== DD Safety Check ==="
echo "Source: $SOURCE"
echo "Destination: $DEST"
echo ""

# Check if devices exist
if [ ! -b "$SOURCE" ]; then
    echo "ERROR: Source device does not exist"
    exit 1
fi

if [ ! -b "$DEST" ]; then
    echo "ERROR: Destination device does not exist"
    exit 1
fi

# Check if mounted
if mount | grep -q "$DEST"; then
    echo "ERROR: Destination is mounted!"
    mount | grep "$DEST"
    exit 1
fi

# Show device info
echo "Source info:"
lsblk -o NAME,SIZE,TYPE,MOUNTPOINT $SOURCE

echo ""
echo "Destination info:"
lsblk -o NAME,SIZE,TYPE,MOUNTPOINT $DEST

# Confirm
read -p "Proceed with dd? This will ERASE $DEST! (yes/no): " confirm

if [ "$confirm" != "yes" ]; then
    echo "Aborted"
    exit 1
fi

echo "Proceeding..."

Error Handling

# Proper error handling
#!/bin/bash

SOURCE=/dev/sda
DEST=/backup/sda.img
LOG=/var/log/dd-backup.log

# Log function
log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a $LOG
}

log "Starting backup: $SOURCE -> $DEST"

# Run dd with error handling
if dd if=$SOURCE of=$DEST bs=1M conv=sync,noerror status=progress 2>&1 | tee -a $LOG; then
    log "Backup completed successfully"

    # Verify
    log "Calculating checksum..."
    md5sum $SOURCE > ${DEST}.md5

    log "Backup and verification complete"
else
    log "ERROR: Backup failed with exit code $?"
    exit 1
fi

Safe Testing

# Test dd commands safely

# 1. Test with small file first
dd if=/dev/zero of=/tmp/test.img bs=1M count=100
dd if=/tmp/test.img of=/tmp/test2.img bs=1M
cmp /tmp/test.img /tmp/test2.img

# 2. Use of=/dev/null for read tests
dd if=/dev/sda of=/dev/null bs=1M count=100

# 3. Verify parameters with echo
echo "dd if=/dev/sda of=/dev/sdb bs=1M status=progress"
# Review before executing

# 4. Use screen/tmux for long operations
screen -S dd-backup
sudo dd if=/dev/sda of=/backup/sda.img bs=1M status=progress
# Ctrl+A, D to detach

# 5. Always verify after clone
sudo md5sum /dev/sda > /tmp/source.md5
sudo md5sum /dev/sdb > /tmp/dest.md5
diff /tmp/source.md5 /tmp/dest.md5

This comprehensive guide covers all major dd operations for disk imaging, data recovery, wiping, and advanced data manipulation with safety best practices.