#StackBounty: #bash #shell-script #chroot chroot fails to be executed more than once in a while loop

Bounty: 100

Description

Very same loop containing chroot command can be executed in terminal but can not be executed within a shell script.

Reproduction

  1. Create a basic (or copy of your) rootfs in /mnt/myrootfs
  2. Create a file in /mnt/myrootfs/tmp/hello.sh (and make it executable) with the following contents:
    #!/bin/bash
    echo "i am exiting."
    exit 
    
  3. Create the following script (./chroot-poll.sh):
    #!/bin/bash
    while sleep 1; do 
        echo "chrooting into the target..."
        sleep 1    
        sudo chroot /mnt/myrootfs /bin/bash --rcfile /tmp/hello.sh
    done
    

Result

Console output is as follows:

$ ./chroot-poll.sh 
chrooting into the target...
i am exiting
chrooting into the target...

[1]+  Stopped                 ./chroot-poll.sh

Why is this stopping? Bringing it foreground by fg makes it iterate once more, and it stops again.

Running within a terminal works:

Copying the contents of ./chroot-poll.sh and pasting directly into the terminal works as expected:

$ while sleep 1; do      echo "chrooting into the target...";     sleep 1    ;     sudo chroot /mnt/myrootfs /bin/bash --rcfile /tmp/hello.sh; done
chrooting into the target...
i am exiting
chrooting into the target...
i am exiting
chrooting into the target...
i am exiting
chrooting into the target...
i am exiting
chrooting into the target...
^C

Question

Why contents of a script can work in a terminal while script itself fails to execute?


Get this bounty!!!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.