Executing function inside chroot in bash

3.4k views Asked by At

What would be the ideal way to pass a function into a chroot from the host, in bash?

For example,

install_script () {
    wget some_source_files && configure && make && make install
}

and,

some_command -v foo >/dev/null 2>&1 || install_script

but if i want to execute the same from the host into chroot, How do i go about doing it?

One way i can think of is to pass the function to a file inside the chrooted directory,

cat > $chrooted_dir/etc/install_script.sh <<"EOF"

#!/bin/bash
wget source_files ; ./configure ; make ; make install

EOF

and execute from host,

chroot $chrooted_dir /bin/bash "check_command  || /etc/install_script.sh"

But i am wondering if there is a more elegant way to approach this? Ideally, i would like to execute the commands from a cript in the host and have some installation performed inside chroot system.

P.S: I would also appreciate of any relevant sources/links to understand bash handles function declarations and subsequent inherits on chrooting.

1

There are 1 answers

0
that other guy On

You can export functions and execute them in an inheriting shell:

install_func () {
    wget some_source_files && configure && make && make install
}
export -f install_func
chroot "$chrooted_dir" /bin/bash -c "install_func"

The function will be turned into an environment variable with the name BASH_FUNC_install_func%%, which will be inherited and reinterpretted as a function by the chrooted bash.