8 Creating a SD card for the Raspberry Pi - PolytechAngersMecatroniqueClub/Tutorials GitHub Wiki

This is the method detailed here : https://medium.com/platformer-blog/creating-a-custom-raspbian-os-image-for-production-3fcb43ff3630. It is assumed you have an SD card with your custom parametrized OS to want to copy/save, and you use a computer running Ubuntu (18.04 in my case).

Clone the full sd card

Plug the SD card into your computeur.

Find out the name of the mount

Use the command

sudo fdisk -l

to find out the name of the SD card. You should have something like:

Device         Boot  Start      End  Sectors  Size Id Type
/dev/mmcblk0p1 *      8192   270335   262144  128M  c W95 FAT32 (LBA)
/dev/mmcblk0p2      270336 62332927 62062592 29,6G 83 Linux

or

Device         Boot  Start      End  Sectors  Size Id Type
/dev/sdb1 *      8192   270335   262144  128M  c W95 FAT32 (LBA)
/dev/sdb2      270336 62332927 62062592 29,6G 83 Linux

but you do not want

/dev/loop

It may means that the SD card is not plugged into the computer.

Copy the SD card content

Then you can use the dd command to copy all you SD file content into a file (bit by bit).

sudo dd if=/dev/mmcblk0 of=/your/path/to/clone.img

You may change the if value to meet your configuration (for instance if=/dev/sdb). Note that you should not use the last number of the fdisk output!

It may takes a while, depending on the size of your SD card.

Shrink the image

To do that you can use a script pishrink.sh available online : https://raw.githubusercontent.com/Drewsif/PiShrink/master/pishrink.sh.

First download the file:

wget  https://raw.githubusercontent.com/Drewsif/PiShrink/master/pishrink.sh

Then add the execution authorization to it:

chmod +x pishrink.sh

Finally you can use the script to shrink your image

sudo ./pishrink.sh /your/path/to/clone.img /your/path/to/clone-shrink.img

You should have an output saying how shrinked the image was. For instance I had a 32Go SD card with xubuntu and ROS installed, that has been shrinked to a 5Go image.

Install the image on a new SD card

You can use the startup disk creator tool of ubuntu to copy your .img file on the SD card. Then you will have to use gparted to resize the "ubuntu-rootfs" partition in order to occupy all the available memory on you SD card.