Automate chroot into broken system

chrootgrub

Every time you have to mount a system with a live-boot-CD and chroot into the system to repair grub, you have to type so many lines to mount into the right partition:

fdisk -l

find the right partition for example /dev/sda1

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

Is there a way to optimize this with a single script?

Best Answer

Copy this script as mount-root on your usb-device

#!/bin/bash
if [ "$(whoami &2>/dev/null)" != "root" ] && [ "$(id -un &2>/dev/null)" != "root" ] ; then
 echo "You must be root to run this script!"; echo "use 'sudo !!'"; exit 1
fi


if [ $# -ne 2 ]; then
 echo "calling this script with only two options with the device and mountpoint"
 echo "for example"
 echo "mount-root /dev/sda1 /media/other/"
 set -x
 fdisk -l
 lsblk -f
 exit
fi

D=$(echo $1 | sed 's:/$::')
M=$(echo $2 | sed 's:/$::')

echo mounting $D to $M

mkdir -p $M

mount $D $M
mount -t proc none $M/proc
mount -o bind /dev $M/dev
mount -t sysfs sys $M/sys
mount --bind /dev/pts $M/dev/pts
cp /proc/mounts $M/etc/mtab
chroot $M/ /bin/bash

source: https://gist.github.com/rubo77/eac3313ea5302acfca60

Related Question