Skip to content

Instantly share code, notes, and snippets.

@nnsee
Last active May 16, 2021 23:32
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nnsee/ab9675d9c5183e875bb49e4d4831f2f4 to your computer and use it in GitHub Desktop.
Save nnsee/ab9675d9c5183e875bb49e4d4831f2f4 to your computer and use it in GitHub Desktop.
OpenWRT chroot helper script
#!/bin/bash
# script to mount and chroot into a rootfs directory
# designed for openwrt systems, but should work for anything with minimal modifications
# unless you specify a different chroot dir,
# place script on the same level as the rootfs directory, should look something like so:
# /mnt/
# |- chroot.sh
# |- rootfs/
# |- bin/
# |- etc/
# [...]
# usage is same as regular chroot command - no args implies 'chroot ./rootfs/ /bin/bash'
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
if [ $# -ge 1 ]
then
ROOTFS="$1"
else
ROOTFS="${DIR}/rootfs"
fi
if [ $# -lt 2 ]
then
ARGS="/bin/bash"
else
ARGS="${@:2}"
fi
{
{ mount | grep -e "on ${DIR} .*noexec"; } && mount ${DIR} -o exec,remount
{ mount | grep "on ${ROOTFS}/proc"; } || mount -t proc proc ${ROOTFS}/proc/
{ mount | grep "on ${ROOTFS}/sys"; } || mount -t sysfs sys ${ROOTFS}/sys/
{ mount | grep "on ${ROOTFS}/tmp"; } || mount -o bind /tmp ${ROOTFS}/tmp/
{ mount | grep "on ${ROOTFS}/dev"; } || mount -o bind /dev ${ROOTFS}/dev/
{ mount | grep "on ${ROOTFS}/dev/pts"; } || mount -t devpts /dev/pts ${ROOTFS}/dev/pts/
cp /etc/resolv.conf ${ROOTFS}/etc/resolv.conf
} >/dev/null 2>&1
chroot ${ROOTFS} ${ARGS}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment