Skip to content

Instantly share code, notes, and snippets.

@dryliketoast
Last active March 22, 2026 22:12
Show Gist options
  • Select an option

  • Save dryliketoast/00dd8cc455f50d5cb97a85b3aff0d27f to your computer and use it in GitHub Desktop.

Select an option

Save dryliketoast/00dd8cc455f50d5cb97a85b3aff0d27f to your computer and use it in GitHub Desktop.
The Chroot Automator (mount-chroot.sh)
#!/bin/bash
# Usage: sudo ./mount-chroot.sh /dev/mapper/ubuntu--vg-root /dev/sda2 /dev/sda1
# Params: 1: Root device, 2: Boot partition (optional), 3: EFI partition (optional)
#Execution Workflow
#Unlock LUKS first:
#cryptsetup luksOpen /dev/sda3 crypt_root
#Run script:
#chmod +x mount-chroot.sh
#sudo ./mount-chroot.sh /dev/mapper/crypt_root /dev/sda2 /dev/sda1
ROOT_DEV=$1
BOOT_DEV=$2
EFI_DEV=$3
TARGET="/mnt/chroot"
if [[ $EUID -ne 0 ]]; then
echo "This script must be run as root"
exit 1
fi
if [[ -z "$ROOT_DEV" ]]; then
echo "Usage: $0 <root_dev> [boot_dev] [efi_dev]"
exit 1
fi
echo "--- Preparing Chroot Environment at $TARGET ---"
# 1. Mount Root
mkdir -p $TARGET
mount $ROOT_DEV $TARGET
# 2. Mount Boot/EFI if provided
if [[ -n "$BOOT_DEV" ]]; then
mount $BOOT_DEV $TARGET/boot
fi
if [[ -n "$EFI_DEV" ]]; then
mount $EFI_DEV $TARGET/boot/efi
fi
# 3. Bind API Filesystems
echo "--- Binding Kernel API Filesystems ---"
for dir in /dev /dev/pts /proc /sys /run; do
mount --bind $dir $TARGET$dir
done
# 4. Copy DNS config to ensure networking inside chroot
cp /etc/resolv.conf $TARGET/etc/resolv.conf
echo "--- Entering Chroot ---"
chroot $TARGET /bin/bash
# 5. Cleanup after exiting chroot
echo "--- Chroot exited. Unmounting... ---"
umount -l $TARGET/dev/pts
umount -l $TARGET/dev
umount -l $TARGET/proc
umount -l $TARGET/sys
umount -l $TARGET/run
if [[ -n "$EFI_DEV" ]]; then umount $TARGET/boot/efi; fi
if [[ -n "$BOOT_DEV" ]]; then umount $TARGET/boot; fi
umount $TARGET
echo "--- Done ---"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment