3 # chroot_wrapper.sh - simplistic wrapper to make chroot more practical
5 # Copyright (C) 2016 Antonio Ospite <ao2@ao2.it>
7 # This program is free software. It comes without any warranty, to
8 # the extent permitted by applicable law. You can redistribute it
9 # and/or modify it under the terms of the Do What The Fuck You Want
10 # To Public License, Version 2, as published by Sam Hocevar. See
11 # http://sam.zoy.org/wtfpl/COPYING for more details.
15 [ "x$1" = "x" ] && { echo "usage: $(basename $0) <NEWROOT> [<COMMAND>]" 1>&2; exit 1; }
21 [ "x$COMMAND" = "x" ] && COMMAND="/bin/bash"
23 [ "$(id -u)" = "0" ] || { echo "Run this script as root." 1>&2; exit 1; }
26 mount --bind /dev ${NEWROOT}/dev
27 mount --bind /dev/pts ${NEWROOT}/dev/pts
28 mount --bind /proc ${NEWROOT}/proc
29 mount --bind /sys ${NEWROOT}/sys
30 mount --bind /run ${NEWROOT}/run
31 mount --bind /tmp ${NEWROOT}/tmp
36 umount ${NEWROOT}/tmp || :
37 umount ${NEWROOT}/run || :
38 umount ${NEWROOT}/sys || :
39 umount ${NEWROOT}/proc || :
40 umount ${NEWROOT}/dev/pts || :
41 umount ${NEWROOT}/dev || :
45 trap '_umount_prereq' 0
46 trap "exit 2" 1 2 3 15
48 # Unshare the UTS namespace.
49 # This ensures that the hostname change affects only the chrooted process.
50 # WIthout "unshare --uts" the host system hostname would be changed too.
51 # An alternative way would have been to use a tool like chname:
52 # http://blog.marineau.org/post/46688543379/giving-chroot-its-own-hostname-chname
53 unshare --uts chroot ${NEWROOT} /bin/bash -c "hostname -F /etc/hostname && exec ${COMMAND}"