Bash Scripting – How to Reuse a Function in Multiple Scripts

bashfunctionscripting

In bash, sometimes I would like to reuse a function in several scripts.
Is it bad to repeat the definition of the function in all the scripts?
If so, what is some good practice?

Is the following way a good idea?

  • wrap the definition of a function myfunction in its own script define_myfunction.sh,
  • in any script where the function is called, source define_myfunction.sh , and then call the function myfunction arg1 arg2 ....

Thanks.

Best Answer

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.