I like to keep a fairly current backup of the SD card out of my Pi so that if (or when) it goes bugger-up I can easily put it back to how it was instead of downloading a fresh Raspian image and then setting it all up again.
There are usually things on the card that I don't need to preserve as I already have multiple copies so the process detailed below shows how to copy the SD card contents to a Linux computer, do whatever editing that is desired and then shrink the resulting image for storage. Finally there are instructions on how to copy that to a new SD card.
The shrinking uses a script called PiShrink which is available from here. After copying that to your computer make sure that it is executable and in a directory that is in your PATH.
Most of these operations take bloody ages, around twenty minutes, and don't necessarily produce an output while working so don't panic if nothing seems to be happening.
Firstly run:--
lsblk
to see where the SD card is — usually sdf
.
To back it up run:--
sudo dd if=/dev/sdf of=Pi.img bs=1M
To mount image for editing:--
sudo fdisk -l Pi.img
This will give an output something like this:--
255 heads, 63 sectors/track, 1925 cylinders, total 30930944 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x7442af85
Device Boot Start End Blocks Id System
Pi.img1 8192 96663 44236 c W95 FAT32 (LBA)
Pi.img2 98304 30930943 15416320 83 Linux
Multiply Sector Size (512) by Start (98304) which gives an offset of 50331648
Now make a temporary directory and then run:--
sudo mount -o loop,offset=50331648 Pi.img ~/temp
Obviously change ~/temp
to suit your temporary directory.
You'll now be able to do whatever editing you like.
When you've finished run:--
sudo umount ~/temp
To shrink the image:--
sudo pishrink.sh ORIGINAL_IMAGE NEW_IMAGE
Needs space for two copies of the full-sized image. NEW_IMAGE
can be omitted to re-size the original but if it goes wrong you're screwed.
The size of the resulting shrunk image can be further reduced by putting it in an archive. It would then need extracting before it could be put back onto an SD card so whether it's worth doing or not depends on how much hard disk space you've got to spare.
To copy the image to an SD card:--
sudo dd bs=4M if=Pi.img of=/dev/sdf conv=fsync
Click HERE to get this guide as a PDF.