Created
April 7, 2020 01:55
-
-
Save nilox94/c8dfd2f059baa13051827395633d2354 to your computer and use it in GitHub Desktop.
chroot from live cd
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /bin/bash | |
# select target root partition | |
if [ $1 ] | |
then | |
root=$1 | |
else | |
# asuming the system is at the first ext partition | |
root=/dev/`lsblk -f | awk ' | |
$2 ~ "ext" { | |
print substr($1, 3); | |
exit; | |
} | |
'` | |
fi | |
if [ $2 ] | |
then | |
efi=$2 | |
else | |
# select first vfat partition that is not inside an iso image (that should be the EFI) | |
iso=`lsblk -f | awk ' | |
$1 ~ "^s" && $2 ~ "iso" { | |
print $1 | |
} | |
'` | |
efi=/dev/`lsblk -f | awk -v iso=$iso ' | |
BEGIN { | |
gsub("\n", "|", iso); | |
} | |
$1 !~ iso && $2 == "vfat" { | |
print substr($1, 3); # remove |- prefix | |
exit; | |
} | |
'` | |
fi | |
echo "selected '$root' as target root partition" | |
echo "selected '$efi' as target EFI partition" | |
read -p "Do you want to continue? [y/N] " -n 1 -r | |
echo | |
if [[ ! $REPLY =~ ^[Yy]$ ]] | |
then | |
echo 'usage:' | |
echo ' sudo ./livecd2chroot.sh [/root/partition/device/path [/efi/partition/device/path]]' | |
exit 1 | |
fi | |
# prepare new root fs as it is stated in the superuser community wiki | |
# https://superuser.com/questions/111152/whats-the-proper-way-to-prepare-chroot-to-recover-a-broken-linux-installation | |
# mount fs | |
umount $root 2>/dev/null | |
umount $root 2>/dev/null | |
mount $root /mnt | |
mount --bind /proc /mnt/proc | |
mount --bind /sys /mnt/sys | |
mount --bind /dev /mnt/dev | |
mount --bind /run /mnt/run | |
mount $efi /mnt/boot/efi | |
# copy network config | |
cp -L /etc/resolv.conf /mnt/etc/resolv.conf | |
# setup .bashrc | |
# add fancy prompt | |
echo 'export PS1="(chroot) $PS1"' >> /mnt/root/.bashrc | |
# update mtab (to operate grub) | |
echo 'grep -v rootfs /proc/mounts 2>/dev/null > /etc/mtab' >> /mnt/root/.bashrc | |
# ch[ange-]root!! | |
chroot /mnt /bin/bash | |
# restore .bashrc | |
sed -i '$d' /mnt/root/.bashrc | |
sed -i '$d' /mnt/root/.bashrc | |
# unmount fs | |
umount /mnt/boot/efi | |
umount /mnt/{proc,sys,dev,run} | |
umount /mnt |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment