scripting chroot, how to?

Create a second script (e.g. chroot.sh) and place it in your chroot/ folder.

Now edit the command in your original script to this:

chroot chroot/ ./chroot.sh

Now the script chroot.sh will be executed inside your chroot.


you should go with simple solution like pipe:

cat << EOF | chroot chroot
rm -rf /
EOF

PS. joking about rm -rf, anything inside EOF is run inside your chrooted directory, you can also use sudo if you like:

cat << EOF | sudo chroot chroot
ls /
EOF

The thing about chroots and /proc, /sys and /dev/pts is that these three filesystems are provided by the kernel, so they remain the same whether you mount within the chroot or from without. Indeed, you'll see, earlier on in the instructions:

sudo mount --bind /dev chroot/dev

/dev is populated by the kernel, but is not a kernel-provided filesystem, so it had to be bind-mounted. Therefore, in practice, you'll see that mounting it using bind mounts (or otherwise) before entering the chroot works just as well (assume sudo):

for i in dev proc sys dev/pts
do
    mount -o bind /$i chroot/$i
done
chroot chroot
for i in dev/pts proc sys dev
do
    umount -chroot/$i
done
# or
mount -o bind /dev chroot/dev
mount -t sysfs none chroot/sys
mount -t proc none chroot/proc
mount -t devpts none chroot/dev/pts
chroot chroot
for i in dev/pts proc sys dev
do
    umount -chroot/$i
done

Relevant reading:

  • mount dev, proc, sys in a chroot environment?
  • Which of proc, sys etc. should be bind-mounted (or not) when chrooting into a “replacement” distribution?
  • Automate chroot into broken system

Tags:

Bash

Chroot