Skip to content

Instantly share code, notes, and snippets.

@E5ten
Created October 22, 2018 16:05
Show Gist options
  • Save E5ten/f497197b78a30e3bf1645b603abae4bc to your computer and use it in GitHub Desktop.
Save E5ten/f497197b78a30e3bf1645b603abae4bc to your computer and use it in GitHub Desktop.
chroot wrapper that mounts important filesystems and copies resolv.conf beforehands to make internet, sudo, and more work correctly inside the chroot
#!/bin/bash
[[ ! "$(id -u)" = "0" ]] && echo "This script must be ran as root!" && exit 1
CHROOTDIR="$(readlink -f $1)"; shift
# Functions
mount_dirs() {
! mount | grep "$CHROOTDIR$1" &>/dev/null && mount --bind "$1" "$CHROOTDIR$1"
}
umount_dirs() {
umount "$CHROOTDIR$1"
}
# Main
cp /etc/resolv.conf "$CHROOTDIR"/etc/resolv.conf
dirs=("/proc" "/sys" "/dev" "/dev/shm" "/dev/pts")
for dir in ${dirs[@]}; do
mount_dirs "$dir"
done
chroot "$CHROOTDIR" $@
udirs=("/proc" "/sys" "/dev/shm" "/dev/pts" "/dev")
for udir in ${udirs[@]}; do
umount_dirs "$udir"
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment