Backup and Restore a Disk Image In Linux

Here’s a simple and easy way of making a backup image of your disk. It uses dd (used for low-level copying) to copy either an entire disk or just one partition, into either a gzipped file or onto another disk.

Backup

To backup to a gzipped file, we will pipe all of the data into gzip and save it to a file. Remember to first change “sda” in the following command to the drive or partition you would like to backup (e.g. sdb, sdb1 etc.), then change the location of the file to wherever you want to save it. If you like, you can change the compression level to speed things up a bit (or increase the compression), the “-9” represents the compression level with 1 being the least (and fastest) and 9 being the most (and slowest). The bs switch stands for blocksize, generally, the higher the value, the quicker the copy will be. The default value is 512 bytes which will take an very long time when copying a large disk, I generally use bs=2048.  When using these methods, make sure the device you are writing to is large enough to write all of the data to. The command to run is as follows:

dd if=/dev/sda bs=2048 | gzip -9 > /media/backup.gz

If you dont want to save it to a compressed file and would rather write everything straight to another disk, use the following command:

dd if=/dev/sda of=/dev/sdb bs=2048

This will write everything on sda to sdb.

Progress

As dd doesn’t show you the progress of the copy, we need to open another terminal to find out. First off, we need to find out the pid of dd, to do that, run the following command:

pgrep -l '^dd$'

This should return something like:

3178 dd

So we now know that the pid of dd is 3178. Now to show the current status of dd, run the following command (don’t worry, it won’t kill the process!):

kill -USR1 3178

You should then get some output along the lines of the following:

2397606+0 records in
2397605+0 records out
1227573760 bytes (1.2 GB) copied, 86.3189 s, 14.2 MB/s

Restore

So, once all of the data has been written, you may want to restore the backup elsewhere. To restore the backup from the file, run the following command (remember to change drives and paths):

gunzip -c /media/backup.gz | dd of=/dev/sda bs=2048

Or, if you are writing straight to disk:

dd if=/mnt/sdb of=/dev/sda bs=2048

All done, simple and easy!

Leave a Reply

Your email address will not be published. Required fields are marked *