Hamid Fadishei's Blog

April 26, 2010

Linux chroot: do it perfectly!

Filed under: Linux — fadishei @ 8:26 am

Today, like many other days since I know Linux, I needed to re-install Grub on a system. The problem was that I could not boot into it. The even greater problem was that I wanted to use exactly the grub-install of the same system that I could not boot into. The solution I use in the situations like this is to boot into the system using a live-cd or anything that can drop me in a simple Linux shell (even without providing the grub-install command in that shell) and then chroot into the Linux installation I want to install grub and use its grub-install.

But simply issuing a chroot command to the mounted root is not a really perfect changing of root! You should make the special filesystems available to the target root system at first. Otherwise, you may encounter an empty /dev, and empty /proc, etc after chroot. Thus the grub-install will complain that it can not find your hard disk device nodes.

So, what you should do is to make the special filesystems available to the new root after mounting it:

# mount the target root:
mount /dev/sda2 /mnt

# mount the special filesystems:
mount -o bind /proc /mnt/proc
mount -o bind /dev /mnt/dev
mount -o bind /sys /mnt/sys

# now chroot!
chroot /mnt

# mount extra partitions if you have them separate
mount /dev/sda1 /boot
mount /dev/sda5 /var

# now you shall have no problems after issuing a grub-install
grub-install /dev/sda

Blog at WordPress.com.