Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an .IMG image of a disc (sd card) without including free space?

Tags:

linux

image

dd

In Linux, we can do

dd if=/dev/sdb of=bckup.img 

but if the disk is of 32GB with only 4GB used, the 32GB image file is waste of space-time. Is there any way or tool to create images with only valid data?

like image 940
Necktwi Avatar asked Oct 14 '13 07:10

Necktwi


People also ask

Does DD copy blank space?

dd doesn't care what the data it copies means. Partition tables, partition contents, file fragments, empty filesystem space, it's all bytes.


2 Answers

Pretty good and simple way to deal with this is simply pipe it via gzip, something like this:

# dd if=/dev/sdb | gzip > backup.img.gz 

This way your image will be compressed and most likely unused space will be squeezed to almost nothing.

You would use this to restore such image back:

# cat backup.img.gz | gunzip | dd of=/dev/sdb 

One note: if you had a lot of files which were recently deleted, image size may be still large (deleting file does not necessarily zeroes underlying sectors). You can wipe free space by creating and immediately deleting large file containing zeros:

# cd /media/flashdrive # dd if=/dev/zero of=bigfile bs=1M     # let it run and quit by disk full error # rm bigfile 
like image 134
mvp Avatar answered Oct 08 '22 22:10

mvp


The best thing to do is

  1. Copy all the files from all the partitions preserving meta data

    mkdir -p myimage/partition1

    mkdir myimage/partition2

    sudo cp -rf --preserve=all /media/mount_point_partition1/* myimage/partition1/

    sudo cp -rf --preserve=all /media/mount_point_partition2/* myimage/partition2/

  2. Extract the MBR

    sudo dd if=/dev/sdX of=myimage/mbr.img bs=446 count=1

    replace /dev/sdX with the corresponding device.

  3. Partition the destination disk into partitions with sizes greater than copied data and should be of the same format and same flags using gparted. Google how to partition a disk.

  4. Mount the freshly formatted and partitioned disk. On most computers, you just need to connect the disk and you can find the mounted partitions in /media folder.

  5. Copy the previously copied data to destination partitions using following commands

    sudo cp -rf --preserve=all myimage/partition1/* /media/mount_point_partition1/

    sudo cp -rf --preserve=all myimage/partition2/* /media/mount_point_partition2/

  6. Copy back the MBR

    sudo dd if=myimage/mbr.img of=/dev/sdX bs=446 count=1

Now njoy Ur new disk!

like image 30
Necktwi Avatar answered Oct 09 '22 00:10

Necktwi