How shall I reuse a function in multiple scripts?

In bash, that is a good way of doing it, yes.

Sourcing the "library" script using source or . would be an adequate solution to your issue of wanting to share a function definition between two or more scripts. Each script that needed access to the function(s) defined in the "library" script(s) would source the needed file(s), probably at the top of the script.

This would allow you to collect related functions in a single "library" script and source it to get access to them.

Not entirely unrelated, but the bash shell also has the ability to automatically source a file upon executing a non-interactive shell (i.e. a script). This may be used to set up a specific environment for the script:

BASH_ENV="$HOME/stuff/script.env" ./myscript

... where script.env may do anything from defining functions and setting shell or environment variables, to sourcing other files etc.


Some shells, like ksh93, has an environment variable that points to a directory that may contain function definition scripts like these. In ksh93, this variable is called FPATH. A script, $FPATH/foo, would contain a function called foo, which would automatically be found when the user types foo on the command line (or in a script). The bash shell does to my knowledge not have this specific functionality.

Other shells have other forms of "auto-load" functionality.