Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shell Script that does chroot and execute commands in chroot

Tags:

bash

shell

chroot

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 ??

like image 469
Mayank Kataruka Avatar asked Jul 12 '18 12:07

Mayank Kataruka


People also ask

What is chroot path?

A chroot (short for change root) is a Unix operation that changes the apparent root directory to the one specified by the user. Any process you run after a chroot operation only has access to the newly defined root directory and its subdirectories.

Does openSUSE use bash?

The default shell in openSUSE® Leap is Bash (GNU Bourne-Again Shell).


2 Answers

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.

like image 197
Ondrej K. Avatar answered Nov 03 '22 23:11

Ondrej K.


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]...]

like image 37
Mayank Kataruka Avatar answered Nov 03 '22 22:11

Mayank Kataruka