Skip to content

Instantly share code, notes, and snippets.

@stbuehler
Last active December 27, 2021 16:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stbuehler/42a6b80934ba945ad0cbdc6f3c6976d5 to your computer and use it in GitHub Desktop.
Save stbuehler/42a6b80934ba945ad0cbdc6f3c6976d5 to your computer and use it in GitHub Desktop.
mount rootfs from livecd to repair grub / ...
# Find block device names for main disk, rootfs and /boot (if it is on a separate partition; usually with encrypted rootfs)
# your main disk isn't necessarily /dev/sda anymore; NVMe disks have names like /dev/nvme0n1
# -> /dev/sda might as well be the "livecd"
# For UEFI boot you should also identify the EFI partition; EFI requires a gpt PTTYPE.
lsblk -p -o NAME,RM,SIZE,RO,PTTYPE,TYPE,FSTYPE,MOUNTPOINT,LABEL,PARTLABEL
# or use `lsblk -p; blkid` instead of the long lsblk command
# If you run mdadm raid, probably should start with that. Instructions not included (yet).
# If encrypted rootfs: open it
cryptsetup open /dev/${cryptpart} ${cryptpart}_crypt
# Maybe a LVM layer between?
vgscan
vgchange -ay
# check block devices again, should now show rootfs volume:
lsblk -p -o NAME,RM,SIZE,RO,PTTYPE,TYPE,FSTYPE,MOUNTPOINT,LABEL,PARTLABEL
# now build a chroot for the actual system at /mnt (or any other location you want;
# should be an empty directory, you can create a new one)
#
# this happens in a separate mount namespace to make it easier to cleanup
# <<< MOUNT NS START >>>
unshare --mount ## starts a subshell; "exit" will leave it, the kernel should remove all mounts once the last process using the NS goes down
mount /dev/${rootfs} /mnt
mount /dev/${bootfs} /mnt/boot # with separate /boot
mount /dev/${efifs} /mnt/boot/EFI # with UEFI boot
for t in /proc /sys /dev /run /tmp; do mount --rbind "${t}" "/mnt${t}"; done
# for network access in chroot you might have to edit /mnt/etc/resolv.conf, or try bind-mounting it like this:
mount --bind $(readlink -f /etc/resolv.conf) /mnt/etc/resolv.conf
# (otherwise DNS might not work in chroot)
chroot /mnt bash --login
# or just: chroot /mnt
## now repair whatever needs repairing, e.g:
update-initramfs -u
grub-install /dev/${disk}
exit # exit chroot
exit # exit+cleanup mount namespace
# <<< MOUNT NS EXIT >>>
findmnt # shouldn't show mounts from above; that way you know you left the mount NS
vgchange -an # disable LVM
cryptsetup close ${rootfs}_crypt # close crypt
# done.
sync
reboot
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment