To complement @terdon's answer, with Korn-like shells other than
bash that support
typeset -f (ksh, mksh, zsh), or with
bash as well if only to avoid the pitfalls of the function export feature (see below), I suggest some alternatives.
For the shell started by
script to have the same function defined, you can either include the definition of that function before the shell code you're passing to
script -c, which you can obtain with
SHELL=/same/shell/as/running/the/current/script script -c "
$(typeset -f myfunc)
script will start a new shell and that shell will start by defining the function and then invoke it.
Or pass the body of the function in an environment variable¹, and have the shell started by
script evaluate the contents of that variable:
MYFUNC_DEFINITION="$(typeset -f myfunc)" script -c '
(that one has the advantage of not exposing the body of the function in the command line arguments for everybody to see in the output of
The advantages over
export -f (other than not being bash-specific) are that:
- then that function is only exposed to that shell where you need it in, and not the other shells that may be started in that environment.
bash will fail to import a function if that function uses
extglob operators unless the
extglob option was enabled before the function is imported. With our approaches, we get to choose when we import the function definition and can then add a
shopt -s extglob before. But with functions exported with
export -f, the only way we can set the
extglob option early enough is with
bash -O extglob which is not an option here with
env BASHOPTS=extglob script -c ... (which is otherwise dangerous as it affects all
bash invocations) doesn't work.
¹ actually, that's what
bash does internally with
export -f. It even used to do it in a very unsafe fashion which was the root of a very nasty vulnerability that made the news headlines a few years ago..