Change partition order - replace sda1 wih sda2 and so on

Suppose you have this layout:

/dev/sda1 - /
/dev/sda2 - /boot

You now want to have the boot partition before /:

/dev/sda1 - /boot
/dev/sda2 - /

But you want to keep the UUID:s of the partitions, so the UUID of sda1 gets transferred to sda2.

Some things to note here:
- sdaX numbers seems to be just the order of the partitions on the disk.
- UUID:s are noted in the partitions, copying the contents of one partition to another results in a duplicate UUID.
- Grub mostly seems interested in where the boot flag is situated, it checks this partition for initrd:s.
- Initramfs (located in /boot) is built with /etc/fstab, /etc/crypttab.

Boot Gparted live ISO (0.28+ for LUKS encrypted partition support).

If you have encrypted partitions, you may need to open a terminal and unlock them:
cryptsetup luksOpen /dev/sda2 /dev/sda2_crypt

Alternative 1 - copying using Gparted

Cut and paste the partitions in Gparted, it seems to keep the UUID on both the original and the copy.

Alternative 2 - copying using Gparted and dd

Shrink the partitions in Gparted to minimal sizes, note that you may need to reduce in pieces to get through, first reduce 25%, then 25% again and so on. Also remember that Ext4 partitions has 5% reserved free space for system files if not disabled using tune2fs.

Create a new third partition behind /dev/sda2 (/boot) at a size covering /dev/sda1 (/), this will be /dev/sda3.

Then open a terminal and copy the contents of /dev/sda1 to /dev/sda3:
sudo bash
dd if=/dev/sda1 of=/dev/sda3 bs=1024k status=progress

Ensure /dev/sda2 fits in /dev/sda1, if not, resize. Then copy /dev/sda2 to /dev/sda1:
dd if=/dev/sda2 of=/dev/sda1 bs=1024k status=progress

Then remove /dev/sda3 in Gparted, resize and set the boot flag on /dev/sda1.

Mount and update references

For regular root partition:
mount /dev/sda2 /mnt

For LUKS encrypted root partition:
cryptsetup luksOpen /dev/sda2 /dev/sda2_crypt
mount /dev/mapper/sda2_crypt /mnt

mount /dev /mnt/dev
mount -t proc proc /proc
mount -o bind /dev /mnt/dev
mount -o bind /dev/pts /mnt/dev/pts
chroot /mnt
mount -t sysfs sys /sys

Check /etc/fstab, if there are any /dev/sdaX notations there then change them.

Edit /etc/crypttab so the sdaX_crypt lines are correct.

Go to /boot/, remove initrd files, then regenerate them:
update-initramfs -c k all

grub-install /dev/sda

To be on the safe side it may be wiseable to repeat one time from update-initramfs.

There may be more locations in /etc/ to change /dev/sda1 to /dev/sda2 and vice versa, to check in all files there do:
cd /etc
grep -rn "put-sda1-or-sda2-here" --color=auto ./

This is a personal note. Last updated: 2019-06-15 01:06:22.


Don't forget to pay my friend a visit too. Joakim