How to chroot your GNU/Linux distribution
Nota
<Texts surrounded by '<>'> have to be replaced with your own information.
Find your main partition
lsblk | grep '/$' | awk '{ print $1 }'
That command will display the partition or volume group in the case of LVM
For classic FS (i.e. ext4, xfs):
If the result provided by the previous command starts with /dev/, then use the following commands, otherwise, go to LVM part.
sudo -s #if not logged as root mount </dev/replace with your partition to chroot i.e. /dev/vda4> /mnt mount --bind /dev /mnt/dev mount -t proc /proc /mnt/proc mount -t sysfs /sys /mnt/sys mount -t tmpfs tmpfs /mnt/run mkdir -p /mnt/run/systemd/resolve/ echo 'nameserver 1.1.1.1' > /mnt/run/systemd/resolve/stub-resolv.conf chroot /mnt
Note: if you plan to fix your boot loader or update your kernel, check if /boot is not in an another partition. In that case add the partition:
mount /dev/vda1 /mnt/boot
Now you can work on your chrooted distribution, change files as if it is the current OS, modify files, update reinstall software or bootloader.
⚠ Please note that the command exit will end the chroot environment. If you use a script, be sure there is not an exit command that will end that chrooting
Once it's done, to exit back to the origin OS, use the following commands
exit umount /mnt/dev umount /mnt/proc umount /mnt/sys umount /mnt/run umount /mnt exit #if not logged as root originally
If you have mounted /boot as well, add
mount /dev/vda1 /mnt/boot
For lvm volumes:
lvscan
# example of lvscan result: ACTIVE '/dev/cl/root' [10.00 GiB] inherit ACTIVE '/dev/cl/swap' [2.00 GiB] inherit ACTIVE '/dev/cl/home' [1.00 GiB] inherit ACTIVE '/dev/cl/var' [<6.00 GiB] inherit
Follow the same instruction as previously using the following commands. Adjust regarding your own partitionning.
sudo -s #if not logged as root mount /dev/cl/root /mnt/ mount /dev/cl/home /mnt/home/ mount /dev/cl/var /mnt/var/ mount --bind /dev /mnt/dev mount -t proc /proc /mnt/proc mount -t sysfs /sys /mnt/sys mount -t tmpfs tmpfs /mnt/run mkdir -p /mnt/run/systemd/resolve/ echo 'nameserver 1.1.1.1' > /mnt/run/systemd/resolve/stub-resolv.conf chroot /mnt
Once it's done, to exit back to the origin OS, use the following commands
exit umount /mnt/home/ umount /mnt/var/ umount /mnt/dev umount /mnt/proc umount /mnt/sys umount /mnt/run umount /mnt exit #if not logged as root originally
For systemd users
An easier way to do is to use systemd-nspawn
sudo -s #if not logged as root systemd-nspawn -D </dev/replace with your partition to chroot i.e. /dev/vda4>
Once it's done, to exit back to the origin OS, use the following commands
exit
