Skip to content

Instantly share code, notes, and snippets.

@nicklasfrahm
Last active July 18, 2022 21:15
Show Gist options
  • Save nicklasfrahm/8949872de56567b6d0facb287d867c2f to your computer and use it in GitHub Desktop.
Save nicklasfrahm/8949872de56567b6d0facb287d867c2f to your computer and use it in GitHub Desktop.
chroot helper
#!/bin/bash
if [ "$1" != "start" ] && [ "$1" != "stop" ]; then
echo "usage: ./chroot.sh <start|stop> <rootfs>"
exit 1;
fi
ACTION=$1
if [ ! -d "$2" ]; then
echo "error: invalid directory: $2"
exit 1;
fi
FAKEROOT=$2
set -euo pipefail
MOUNTPOINTS=("/tmp" "/dev/null" "/dev/pts" "/dev/random" "/dev/shm" "/dev/urandom" "/proc")
function stop_chroot() {
for MOUNTPOINT in "${MOUNTPOINTS[@]}"; do
echo "unmounting ${FAKEROOT}${MOUNTPOINT}"
umount "${FAKEROOT}${MOUNTPOINT}" 2> /dev/null || true
done
}
function start_chroot() {
for MOUNTPOINT in "${MOUNTPOINTS[@]}"; do
echo "mounting ${MOUNTPOINT} > ${FAKEROOT}${MOUNTPOINT}"
mount -o bind "${MOUNTPOINT}" "${FAKEROOT}${MOUNTPOINT}"
done
chroot "${FAKEROOT}" /bin/bash --login
}
function main() {
if [ "${ACTION}" == "start" ]; then
start_chroot
elif [ "${ACTION}" == "stop" ]; then
stop_chroot
fi
}
main
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment