1

My question:

After the following lines in my script, the script ends unexpectedly. I am trying to enter chroot inside of a bash script. How can I make this work

I am writing a script that installs Gentoo

echo " Entering the new environment"


chroot /mnt/gentoo /bin/bash 

source /etc/profile 

export PS1="(chroot) ${PS1}"
  • Has `PS1` been defined previously? With the shown snippet, `PS1` is accessed before it has been defined. – Zois Tasoulas Sep 26 '21 at 22:29
  • @zois No, I just got that code from [here.](https://wiki.gentoo.org/wiki/Handbook:AMD64/Installation/Base) –  Sep 26 '21 at 23:22
  • "chroot /mnt/gentoo /bin/bash"- at this moment you start new child process, so rest of your script will not be executed until you exit from child bash process. – Saboteur Sep 26 '21 at 23:34
  • @Saboteur Okay, thank you for letting me know. –  Sep 26 '21 at 23:36
  • You can specify a bash script to run inside the chroot like this: https://stackoverflow.com/a/51312156/530160 – Nick ODell Sep 26 '21 at 23:47
  • You are starting an **interactive** bash here. The script does not _end_, it just waits dutifully that you enter something. – user1934428 Sep 27 '21 at 08:26
  • 1
    @zois That wouldn't matter. By default, the expansion of an undefined parameter is an empty string, not an error. – chepner Sep 29 '21 at 19:05

1 Answers1

2

chroot command will start new child bash process, so rest of your script will not be executed until you quit from child bash process. So instead of /bin/bash just run your script in chroot:

chroot /mnt/gentoo myscript.sh

myscript.sh:

#!/bin/bash
echo " Entering the new environment"

source /etc/profile 
export PS1="(chroot) ${PS1}"
Saboteur
  • 1,331
  • 5
  • 12
  • 1
    This doesn't run an interactive shell at all. It runs `myscript.sh` as a script, and when that script exits, so does `chroot`. – chepner Sep 29 '21 at 19:07
  • If you need interactive shell with chroot, raise separate question. This question is about running script. – Saboteur Sep 29 '21 at 19:46