shellvariablesquotingchroot

How do I make chroot run a command in the same directory in the new rootfs as I am in now?


I have various other Linux distros on other partitions and am trying to write a command called "on" that will run a shell command in that distro as the same user and in the same directory as I am in on the host filesystem in a way that preserves arguments containing spaces or wildcard characters.

I have got as far as

#! /bin/sh
# on: Run a command as the same user in the same directory inside a chroot
# Usage: on directory command [args]
chrootdir="$1"
shift
sudo chroot --userspec="`whoami`" "$chrootdir" sh -c "cd \"`pwd`\" && $@"

which will run it as the same user in the same dir, but would fail if there are spaces in the arguments (or the comnand name!).

One solution is a cd-ing wrapper script:

#! /bin/sh
# Run a command in a specified directory
# Usage: runin dir command [args]
cd "$1" && shift && cmd="$2" && shift && exec "$cmd" "$@"

called by

#! /bin/sh
# on: Run a command as the same user in the same directory inside a chroot
# Usage: on directory command [args]
chrootdir="$1"
shift
sudo chroot --userspec="`whoami`" "$chrootdir" runin "`pwd`" "$@"

but the wrapper has to exist in all the chroot environments, which is boring.

Is there a way to make a single command on the host system that makes the "cd" happen in the chroot, correctly preserving all arguments?


Solution

  • Just execute the script and pass the arguments like you do in your script:

    sudo chroot --userspec="$(id -u):$(id -g)" "$1" \
         sh -c 'cd "$1" && shift && exec "$@"' sudosh "$(pwd)" "$@"
    

    Notes: