Define a dynamic function by running this in command line:

eval "ab() { echo test; }"

It runs and prints test.

Put the same statement in a script test.sh and then execute the script. Nothing happens. The function does not get defined.

I assume that is because function gets defined within script but not outside it. So I try adding within the script:

export -f ab

But it doesn't work. How do I export functions from a script to the shell?


You can't export a function or a variable to a parent shell, you can only export to the shell running the script or to child shells.

For a script to change the environment of your current shell, you need to run the script with source or .. e.g. instead of running ./myscript.sh, you'd run . ./myscript.sh

This tells your current shell to run the script itself, rather than spawning a sub-shell to run it in...and thus allows the script to modify the current environment.

  • You cannot export functions to shell descendents. A shell that permits you to do so must be seen as a security risk ans this permits code injection.
    – schily
    Oct 1 '15 at 12:29
  • 1
    Whether you should or not does not change the fact that you can export a function in bash.
    – chepner
    Oct 1 '15 at 16:26

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.