0

The bash export command is used to make functions available in shell processes that are started from running an interactive shell - without defining them in a file loaded at the start like .bashrc.

What would be a good way to export functions. Perhaps put them in a separate file that can be called when export is required. Customarily, sourcing the files containing the declaration of the functions, would not require calls to export.

1 Answer 1

0

Usually it is done by dumping all the functions you need into a 'library script' and then just source it in your actual scripts.

To simplify maintenance, you can put each function into its own script in some dedicated directory. And then, the library script can be a loader like:

#!/bin/bash
# put this into your local /usr/local/bin/bash_library
for s in /usr/local/share/bash-scripts/*.sh
do
   source $s
done

And in you actual scripts you would have

#!/bin/bash
. /usr/local/bin/bash_library
# actual code
6
  • Yes, but I want to focus specifically on how to handle the export part when needed.
    – Vera
    Oct 10, 2022 at 21:35
  • You can do export -f func_name in a script where that function is defined. And it would be available for all scripts called later. But you still need to source the script with function definition, at least in .bashrc. But this will define a function for the shell only. The "library script" I showed, could be used in any kind of scripts.
    – White Owl
    Oct 10, 2022 at 21:48
  • I would like to separate the export part to some other file, then source the export tool file. This means export would not usually be run. Or perhaps a function that exports what is needed, or what the user wants. What do you think about this?
    – Vera
    Oct 10, 2022 at 22:00
  • So you want to have a delayed load? In the user's script first load a list of available functions, and if the script calls some function then load it before usage? No, I do not think it is possible in bash. The only way to lessen the initial load is to split the library into several sections. Like source library_log_function, source library_ncurses_function, etc.
    – White Owl
    Oct 10, 2022 at 22:35
  • And if you follow a one function per file pattern, then you would be able to source this_function. In addition to a more generalized load whole or part of a library.
    – White Owl
    Oct 10, 2022 at 22:38

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .