I have a created a chroot jail in my Ubuntu 14.04 machine using schroot and debootstrap.

Now I want to write a shell script that goes back and forth between my native environment and the chroot.

When I write the commands directly in a shell script it chokes the moment I switch to chroot.

For example:

sudo chroot /JAIL #folder to chroot
echo "Chrooted now"

I get switched to the chroot folder /JAIL however, I don't get the output in echo. It is only when I exit from the chroot to the Host, this output is printed. I inferred that this might have something to do with the user being changed when the when we enter chroot jail.

So, I tried the solutions mentioned in this question How to switch back and forth between users quickly on a single terminal? I also read about heredocs but couldn't get them to work.

Ideally I would like a shell script that has the flow as below:

  1. chroot to jail
  2. Do something there
  3. Move back to Host
  4. Do something here as well
  5. Go back to chroot, and so on..

Simply write the command after chroot:

chroot /jail /path/to/some/command <parameters>

2nd line of man chroot:

NAME chroot - run command or interactive shell with special root directory


  • Yeah that's right, can't believe how I missed that. Thanks. – Nikhilesh Singh Sep 6 '18 at 17:27

The reason why the echo is executed after sudo exits has nothing to do with the user being changed.

Let's simplify the script:

echo "After cat"

The echo command will be executed after cat is finished, as with every other sequence of commands that you write.

If you want some commands executed inside the chroot, you must pass them as parameters to the chroot.

If you have /bin/bash as your login shell, the command

chroot /dir

is equivalent to

chroot /dir /bin/bash -i

That means it starts an interactive shell. You can execute some commands by creating a shell script that is accessible in the chroot, or by specifying them on the command line

chroot /dir /path/to/script

chroot /dir /bin/bash -c 'some commands; more commands'

The chroot program will always wait for the command to finish, although both the script or the command line can start processes in the background.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.