Skip to content

Instantly share code, notes, and snippets.

@clchiou
Last active August 29, 2015 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save clchiou/c3e6d35fafbad06e729a to your computer and use it in GitHub Desktop.
Save clchiou/c3e6d35fafbad06e729a to your computer and use it in GitHub Desktop.
Mount and then enter a chroot environment
#!/bin/bash
set -e
if [[ -z "$1" ]]; then
echo "Usage: $(basename $0) CHROOT_PATH"
exit 1
fi
if [[ ${UID:-$(id -u)} == 0 ]]; then
echo "This script must be run as a non-root user"
exit 1
fi
CHROOT=$(realpath $1)
WHOAMI=$(whoami)
echo "CHROOT=${CHROOT}"
echo "WHOAMI=${WHOAMI}"
MOUNT_CACHE=$(echo $(awk '{print $2}' /proc/mounts))
function do_mount() {
local src="$1"
local args="$2"
local path="$3"
case " ${MOUNT_CACHE} " in
*" ${path} "*)
echo "Path is already mounted: ${path}"
;;
*)
echo "Mount ${path}"
if [[ -n "${src}" ]]; then
sudo mount -n ${args} "${src}" "${path}"
else
sudo mount -n ${args} "${path}"
fi
;;
esac
}
echo "Mounting directories..."
do_mount none '-t proc' ${CHROOT}/proc
do_mount none '-t sysfs' ${CHROOT}/sys
do_mount /dev '-o bind' ${CHROOT}/dev
do_mount /dev/pts '-o bind' ${CHROOT}/dev/pts
echo "Entering chroot..."
sudo chroot ${CHROOT} sudo -i -u ${WHOAMI}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment