18

If in shell script I write

chroot /home/mayank/chroot/codebase
cd SBC

when I run this shell script It does go in the chroot but does not execute the command cd SBC, when I exit chroot then it executes cd SBC.

How can I achieve something that does chroot and execute commands in chroot through shell script ??

PesaThe
  • 7,259
  • 1
  • 19
  • 43
Mayank Kataruka
  • 395
  • 1
  • 2
  • 11
  • 2
    try `chroot /home/whatever "COMMAND"` chroot can have command – Kent Jul 12 '18 at 12:40
  • 1
    chroot /home/whatever "COMMAND" I even tried that, what actually happened was, it didn't go to chroot, but executed that "COMMAND" command successfully .. – Mayank Kataruka Jul 12 '18 at 14:44
  • Moreover, I have many commands, that is to be run under chroot There must be some way ??? – Mayank Kataruka Jul 12 '18 at 14:52
  • `COMMAND` can execute a script in the chroot. – stark Jul 12 '18 at 16:57
  • Possible duplicate of [Pass commands as input to another command (su, ssh, sh, etc)](https://stackoverflow.com/questions/37586811/pass-commands-as-input-to-another-command-su-ssh-sh-etc) – tripleee Jul 13 '18 at 08:05

2 Answers2

18

When you run chroot without telling it what to do, it will try to start chrooted interactive shell session. So your script would "pause" at that point and when you are done with that interactive shell session, it continues out of chroot again.

One of the quick and dirt options would be to abuse here-document, like this:

chroot /home/mayank/chroot/codebase /bin/bash <<"EOT"
cd /tmp/so
ls -l
echo $$
EOT

Which takes all lines up to EOT and feeds them into bash started through chroot. Those double quotes around "EOT" should ensure bash passes the content not trying to expand variables and such. Hence that echo $$ should be PID of the inner chrooted bash.

Ondrej K.
  • 8,841
  • 11
  • 24
  • 39
3

somewhat I found a solution,

chroot /work3/tmp_GU/$build_env/sbcbuild/chroot ./test.sh

after chroot giving a script there is working fine for me.

test.sh present in the chroot folder. All commands in test.sh will be executed in chroot folder.

So basically giving a command after chroot

man chroot

chroot [OPTION] NEWROOT [COMMAND [ARG]...]

Mayank Kataruka
  • 395
  • 1
  • 2
  • 11