Firstly: doing this by remote is inadvisable especially if, like me, you happen to be 70+ miles from your remote pi. It's a very long drive if you screw it up. When you do this fir the first time, do it "remotely" while sitting right next to the pi.
Secondly: yes, this is possible but I've never done it and although I believe I could achieve it, I'm not going to give step by step instructions.
The SD card for raspbian is already partitioned.
- It has the main OS partition (EXT4 formatted, mounted at
- It has the boot partition (FAT32 formatted, mounted at
What you could do is
- Shrink your main OS partition using
fdisk. This is a bad idea with the PI online. But if you want to shoot yourself in your foot then see here: https://linuxconfig.org/how-to-resize-ext4-root-partition-live-without-umount
- add an extra "recovery" EXT4 partition using
- Install a working OS (Raspbian) on the new partition as a sort of "recovery OS".
- Reboot into the recovery OS by changing PARTUUID
/boot/cmdline.txt and rebooting the pi. You can get the PARTUUID of your partitions by typing
- Wipe clean and re-install the main OS partition.
/boot/cmdline.txt back and reboot into your new fresh OS. It's best to check
sudo blkid before doing this, it may have changed.
If you are simply planning to do this in future, then you will do steps 1, 2 and possibly 3 with the pi offline and just leave the recovery partition in place until you need it.
Installing the OS (Steps 3 and 5)
Normally you download an SD card image from the website (https://www.raspberrypi.org/downloads/raspbian/) and just overwrite your entire disk... but that's no good because you must not overwrite your partition table.
The downloaded images will have the exact 2 partitions you started with, so you need to copy the OS partition from the image into whichever partition you want to install to.
So you can try this:
# Download the image file
# Create a loopback device to let you treat the image as a disk
sudo losetup /dev/loop0 2017-11-29-raspbian-stretch-lite.img
# Map the image's partitions
sudo partprobe /dev/loop0
# Completely overwrite one of your partitions with one from the image
# MAKE SURE YOU DON'T HAVE THE PARTITION MOUNTED WHEN YOU OVERWRITE IT
sudo dd if=/dev/loop0p2 of=mmcblk0p2 status=progress
The part of this I really can't help you with is skipping the first boot which usually does something different to simply booting the pi