I backed up my raspbian with dd

dd id=/dev/sdb of=/home/user/raspbian-backup.img

That gives me a img of the whole card (16gb). Then i followed the tutorial in raspberry.org to resize the image and used

truncate --reference 2015-05-05-raspbian-wheezy.img raspbian-backup.img

My question is the next. Will this mesh up my backup image? Is the correct process or the tutorial only will work with "new" images? I dont have any SD to dd'ing my new backup image and try it.

This is the raspberry.org tutorial I have mentioned.

  • If you mean that the filesystem on the card was resized up at some point, yes, this will have wrecked the image, see raspberrypi.stackexchange.com/q/29947/5538 But if you have never changed the filesystem size, then it should be okay (presuming the size of the partitions in the 5-05-15 Raspbian image are the same as the one you used to install). – goldilocks May 22 '15 at 12:15

No that is the wrong way to do it; it makes the bad assumption that there are no files in the truncated part.

The correct way is to mount the img via loopback and resize the fs and partition before truncating:


#get partition offset
S=$(fdisk -l $IMG | grep Linux | perl -pe 's/ +/\t/g' | cut -f 2)
B=$(fdisk -l $IMG | grep Units | perl -pe 's/.*=//g;s/[^0-9]//g')
O=$(echo "$S*$B" | bc)

#shrink file system
L=$(losetup -f --show $IMG -o $O)
e2fsck -f $L
resize2fs -M $L
losetup -d $L

#get new file system size
mkdir $MDIR
mount -o loop,offset=$O $IMG $MDIR
U=$(df -B KB $MDIR | tail -n 1 | perl -pe 's/ +/\t/g' | cut -f 2)
umount $MDIR
rm -r $MDIR

L=$(losetup -f --show $IMG -o $O)
zerofree -v $L
losetup -d $L

#shrink the partition
L=$(losetup -f --show $IMG)
N=$(parted $L print | grep ext4 | perl -pe 's/ +/\t/g' | cut -f 2)
S=$(parted $L unit kB print | grep ext4 | perl -pe 's/ +/\t/g' | cut -f 3)
U=$(echo $U | perl -pe 's/[^0-9]//g' )
S=$(echo $S | perl -pe 's/[^0-9]//g' )
U=$(echo "$U+$S+1" | bc)
S=$(parted $L unit s print | grep ext4 | perl -pe 's/ +/\t/g' | cut -f 3)
parted $L rm $N
parted $L mkpart primary ext4 $S $U"kB"
losetup -d $L

#shrink the img file
E=$(fdisk -l $IMG | grep Linux | perl -pe 's/ +/\t/g' | cut -f 3)
NE=$(echo "($E+1)*$B" | bc)
truncate --size=$NE $IMG

This will shrink the official image by 37% from 3.1G to 2.3G (991M to 628M compressed)

Using zerofree and 7z will make a small file for backup/storage/distribution if you don't want to resize the img file.

  • This is a bash script? – Andi Giga Jun 9 '17 at 8:58
  • @AndiGiga yes; or likely any similar Unix like shell. – user1133275 Jun 9 '17 at 17:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.