Exporting function names

I have some functions defined in my .bashrc. I need some advice regarding the use of the command

export -f func_name

When is export of a function required?

2 Answers

Exporting of functions is required for the same reason as exporting of variables - that is, to make the function definition visible in a child process (specifically, in a child bash shell - unlike the case for variables, other processes - even other shell processes - won't recognize exported bash functions). So for example:

$ declare -p -f foo
foo ()
{ echo 'I am foo'
}
$ bash -c 'foo'
bash: line 1: foo: command not found

but

$ export -f foo
$ bash -c 'foo'
I am foo

Of course, any shell that sources the file in which the function is defined (such as an interactive non-login shell when the function is defined in your ~/.bashrc file) does not need to rely on inheriting it from its parent

$ declare -n -f foo # "unexport" the function
$ declare -f -p foo >> ~/.bashrc
$ bash -c 'foo'
bash: line 1: foo: command not found

but

$ bash -ic 'foo'
I am foo
2

There is a good discussion of the topic here:

In short I would say you don't need to export any functions from .bashrc, because it is anyway sourced, and thus the functions will be available in all your bash sessions right away.

2

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like