Cloning with DD command
How can I backup a partition (not the whole disk) to another partition on an external hard-disk using DD?
I achieved this with the following command:
sudo dd if=/dev/sda6 of=/dev/sdb3 bs=1M
However my requirements are:
I need to backup
/dev/sda6
and store that as an image (.img
) file in/dev/sdb3
Preferably as a compressed (.gz) image file (this is actually what I am trying to achieve)
(Here are my foolish attempts that, obviously, didn't work:
sudo dd if=/dev/sda6 of=/dev/sdb3/backup.img bs=4096 conv=notrunc,noerror
sudo dd bs=1M if=/dev/sda6 | gzip -c > /dev/sdb3/backup.gz
Solution 1:
Unless /dev/sdb3
is actually mounted on /dev/sdb3
( I doubt it, please research a bit on devices and mount points), you'd need to:
- Find out where
/dev/sdb3
is mounted. Use themount
command for this. Assume that/dev/sdb3
is mounted in/home
. -
Point your file writing to that place:
sudo dd if=/dev/sda6 of=/home/backup.img
Once done, verify the img file contains what you expect.
Also, is there any need to back up the entire partition? I usually find it easier and more useful to back up files using rsync
or something similar, then if needed compressing the resulting backup directory. But this is really up to you.
Solution 2:
What you want to do involves 3 simple steps:
- Creating a disk file
- Copying data from partition into the disk file
- Compress the disk file
Creating a disk file
- Mount and CD to the partition where you want to keep a disk file
-
Use
fallocate
to create and preallocate blocks to a disk file. It's much faster than creating a file by filling it with zeros usingdd
or other tools. To specify the disk file size you can useMB/MiB/GB/GiB
prefixes. For example if you want a disk image with size 50 GiB, you do$ fallocate -l 50GiB part_backup.img
-
Format the disk file. In this example, I use
ext4
and disable journaling feature because there's no need for it in this case$ mkfs.ext4 -O '^has_journal' part_backup.img
-
Now that we have our disk file ready, mount the disk file with
losetup
. Pass--show
option to it so it prints the loopback device that your disk file is mounted to, eg/dev/loop0
$ sudo losetup --show -f part_backup.img
-
Create a mount folder in
/mnt
and mount the loopback device to the folder$ sudo mount /dev/loop0 /mnt/my_disk_file
Copying data from partition into the disk file
- Mount the partition that contains files you want to backup and identify the mount point
-
Use
rsync
to copy the files into the disk file you just mounted.$ sudo rsync -avzPSX /mnt/media_partition/ /mnt/my_disk_file
Please look up what each of those rsync opts does in rsync man if you're unusure. Also read the note about trailing slash in backup source
Compress the disk file
-
Unmount the disk file as per normal
$ sudo umount /mnt/my_disk_file
$ sudo losetup -d /dev/loop0
Use
gzip
to compress the disk file