Please tell me how to export a function in parent shell (bash , sh or ksh) so that the function will be available to all the child process launced from the parent process?
If you create subshells with ( )
then they will inherit a snapshot of all the definitions, parameters, and shell variables.
If you execute them like programs then you can put the definitions in .bashrc
.
If you are trying to spoof an existing script into executing a wrapper or substitution for a PATH command, then .bashrc
will work depending on details of the execution. If not, you could instead execute a wrapper script that simply does a .
or source
of an include file that defines the functions and then does the same thing with the shell script with the commands to be substituted.
The wrapper script might look something like:
script=$1
shift
. include.sh
. $script "$@"
The idea is that the first parameter is the name of the real script and remaining parameters are the args, then the above script is run instead.
The export -f
feature is specific to Bash:
parent
#!/bin/bash
plus1 () { echo $(($1 + 1)); }
echo $(plus1 8)
export -f plus1
./child 14 21
child
#!/bin/bash
echo $(plus1 $(($1 * $2)) )
You can use the exvironmental variable FPATH where in you can place all your functions.
if FPATH is set the script first looks in the FPATH directory for the existance of function defnition, if found uses it else it check the definition of the current script. (KSH)
so place all your functions in FPATH location. and child scripts will also be able to find it.
you could use autoload command in side the shell script to load the function you require.
autoload fun_a fun_b;