view sources/root-filesystem/sbin/setup-chroot @ 1446:6d6b25937be2

Fix setup-chroot when used with relative path, and VERBOSE option
author Rob Landley <rob@landley.net>
date Sat, 17 Sep 2011 00:01:20 -0500
parents 18fd34f46508
children
line wrap: on
line source

#!/bin/bash

if [ $# -lt 1 ] || [ "${1:0:1}" == "-" ] || [ "$(readlink -f "$1")" == '/' ]
then
  (
    echo "Usage: setup-chroot NEWDIR [COMMAND...]"
    echo -e "\nCopies root filesystem to NEWDIR and executes COMMAND or /bin/sh"
    echo "If NEWDIR already exists, bind mounts directories instead."
  ) >&2
  exit 1
fi
  
# Copy root filesystem into a new chroot directory and restart in there.

NEWROOT="$1"
shift

dotprogress()
{
  while read i; do echo -n .; done; echo
}

if [ ! -d "$NEWROOT" ]
then
  mkdir -p "$NEWROOT"
  [ -d /mnt/files ] && cp -a /mnt/files/. "$NEWROOT"
  find / -xdev | cpio -m -v -p "$NEWROOT" | dotprogress
fi

# Copy mounts from existing root filesystem to new target.

# Get mount point list, minus the one our new root filesystem is already in,
# then mount --bind each remaining mount point (once) into NEWROOT.

ZAP="$(readlink -f "$NEWROOT")"

for i in $(awk '{print $2}' /proc/mounts | tac)
do
  # De-escape octal versions of space, tab, backslash, newline...
  x=$(echo -e "$i")

  # Skip the entry our chroot is under (generally /home)
  if [ "$x" == "${ZAP:0:${#x}}" ] || [ "$x" == '/' ]
  then
    [ ! -z "$VERBOSE" ] && echo Zapping "$x" >&2
    ZAP=""
    continue
  fi

  echo "$i"
done | tac | while read i
do
  mountpoint -q "$NEWROOT$i" && continue

  [ ! -z "$VERBOSE" ] && echo "Bind $i to $NEWROOT$i" >&2

  mount --bind "$i" "$NEWROOT$i"
done

[ ! -z "$VERBOSE" ] && echo "Chrooting to \"$NEWROOT\"" >&2
chroot "$NEWROOT" "$@"
RC=$?

[ ! -z "$VERBOSE" ] && echo "Cleanup chroot" >&2
zapchroot "$NEWROOT"

exit $RC