Exporting a function in shell Exporting a function in shell shell shell

Exporting a function in shell


The export -f feature is specific to Bash:

parent

#!/bin/bashplus1 () { echo $(($1 + 1)); }echo $(plus1 8)export -f plus1./child 14 21

child

#!/bin/bashecho $(plus1 $(($1 * $2)) )


In sh, it is not possible to export a function, as noted by Charles Duffy.


If you are using ksh or zsh:

You can use the environment variable FPATH, wherein you can place all your functions.

If FPATH is set on an interactive interpreter, and a command or function is not found in the current shell environment or the PATH, the directories listed there are searched for the existence of a file named after the missing command. If one is found, it is sourced in the current shell environment, and expected to define the function.

So, you can place all your functions in a location in FPATH, and child scripts will also be able to find it.

You can use the autoload command in shell scripts to load the functions you require:

autoload fun_a fun_b

In zsh, autoload is required for FPATH to work. In ksh and its close relatives, I believe it simply causes functions defined in FPATH to override regular command in your PATH, as they would if defined directly.

Some details on FPATH and autoload: