alpine-chroot

Various utilities for creating and using Alpine Linux chroots

git clone https://git.8pit.net/alpine-chroot.git

 1#!/bin/sh
 2# Chroots into an existing alpine chroot.
 3
 4set -e
 5
 6##
 7# Variables
 8##
 9
10CHROOT=/usr/sbin/chroot
11USER=root
12
13##
14# Functions
15##
16
17mount_me_maybe() {
18	mountpoint="${1}"
19	shift
20
21	busybox mountpoint -q "${mountpoint}" && return
22	mount "$@" "${mountpoint}"
23}
24
25##
26# Go for it!
27##
28
29if [ $(id -u) -ne 0 ]; then
30	echo "${0##*/} has to be started as root." 1>&2
31	exit 1
32fi
33
34while getopts u: flag; do
35	case "${flag}" in
36		u) USER="${OPTARG}" ;;
37	esac
38done
39
40shift $((OPTIND - 1))
41if [ $# -lt 1 ]; then
42	echo "USAGE: ${0##*/} [-u USER] CHROOT [COMMAND]" 1>&2
43	exit 1
44fi
45
46chrootdir="${1}"
47if [ $# -eq 1 ]; then
48	set -- /bin/su -l "${USER}"
49else
50	shift
51fi
52
53mount_me_maybe "${chrootdir}"/proc -t proc none
54mount_me_maybe "${chrootdir}"/dev  --rbind /dev
55mount_me_maybe "${chrootdir}"/sys  --rbind /sys
56mount_me_maybe "${chrootdir}"/run  --rbind /run
57
58cp -u -L /etc/resolv.conf "${chrootdir}/etc/resolv.conf"
59exec env -i "${CHROOT}" "${chrootdir}" "$@"