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?
To use a function with the export command, use the -f option. If we do not use this option, it will be considered as a variable, not function. Syntax: export -f function_name.
You can use the export command to make local variables global. To make your local shell variables global automatically, export them in your . profile file. Note: Variables can be exported down to child shells but not exported up to parent shells.
Export is a built-in command of the Bash shell. It is used to mark variables and functions to be passed to child processes. Basically, a variable will be included in child process environments without affecting other environments.
The export command, on the other hand, provides the ability to update the current shell session about the change you made to the exported variable. You don't have to wait until new shell session to use the value of the variable you changed. Follow this answer to receive notifications.
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)) )
In sh
, it is not possible to export a function, as noted by Charles Duffy.
Functions are not exportable by nature. However you can export strings, so I have a little trick here:
func="$(typeset -f funcname)"
export func
To import the function, re-define it from the exported string:
# in subshell
eval "$func"
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
:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With