Skip to content

Instantly share code, notes, and snippets.

@ostechnix
Created December 30, 2024 09:51
Show Gist options
  • Save ostechnix/7ca184e32caf6f4e2db8eab9dbeb8259 to your computer and use it in GitHub Desktop.
Save ostechnix/7ca184e32caf6f4e2db8eab9dbeb8259 to your computer and use it in GitHub Desktop.
Chrootmnt: A Bash script to mount and unmount /dev inside a chroot environment.
#!/usr/bin/env bash
# ------------------------------------------------------------------
# Script Name: chrootmnt.sh
# Description: A Bash script to mount and unmount /dev
# inside a chroot environment
# Website: https://gist.github.com/ostechnix
# Version: 1.0
# Usage: ./chrootmnt.sh /path/to/chroot command args
# ------------------------------------------------------------------
# Validate input
if [ $# -lt 2 ]; then
echo "Usage: $0 /path/to/chroot command [args...]"
exit 1
fi
# Path to the chroot directory
CHROOT_DIR="$1"
shift # Remove the first argument (chroot path)
# Ensure the chroot directory exists
if [ ! -d "$CHROOT_DIR" ]; then
echo "Error: Chroot directory $CHROOT_DIR does not exist."
exit 1
fi
# Mount /dev and /dev/pts
sudo mount --bind /dev "$CHROOT_DIR/dev"
sudo mount --bind /dev/pts "$CHROOT_DIR/dev/pts"
# Handle unmounting on exit
cleanup() {
sudo umount "$CHROOT_DIR/dev/pts"
sudo umount "$CHROOT_DIR/dev"
}
trap cleanup EXIT
# Enter the chroot
sudo chroot "$CHROOT_DIR" "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment