Better Code

Swimming in Someone Else's Pool

In-chroot Script

| Comments

This is one of those “use it so much I forget it’s there” scripts. I do a fair amount of system image and package building work. Both of these inevitably involve using chroot, and I can never remember the precise combination of remounts and copies you have to do to make the chroot work “properly”.

Here’s the script I wrote to take care of it for me. It will sudo at the right points, and simply execs its arguments in the chroot (defaulting to /bin/bash if you don’t pass it anything).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#!/bin/bash

if [ -z "${1:-}" ];
then
    echo "usage: ${0} <fsroot>"
    exit 1
fi


if [ -z "${SUDO_USER:-}" ];
then
    sudo $0 $@
    exit $?
fi


FSROOT=${1}
shift

mount proc ${FSROOT}/proc -t proc
mount /dev/pts ${FSROOT}/dev/pts -t devpts
mount /sys ${FSROOT}/sys -t sysfs

cp /etc/resolv.conf ${FSROOT}/etc/resolv.conf

chroot ${FSROOT} "${@:-/bin/bash}"

EXITCODE=$?

umount ${FSROOT}/proc
umount ${FSROOT}/dev/pts
umount ${FSROOT}/sys

exit $EXITCODE

The quoting around executing the command is slightly hairy thanks to bash’s argument array handling, but this does Just Work.

I have this script saved to ~/bin/in-chroot, so I can use it like this:

1
$ in-chroot wheezy-root apt-get update

or

1
2
$ in-chroot wheezy-root
# vi /etc/hosts

and so on. This is something I use almost every day.