7

Say I have these three script files: (all 3 are executable)

bash-test.sh:

#!/bin/bash
HelloFromBash RocketNuts

zsh-test.sh:

#!/bin/zsh
HelloFromZsh RocketNuts

sh-test.sh:

#!/bin/sh
HelloFromSh RocketNuts

As you can tell from the shebangs, these scripts are being executed by different shells i.e. bash, zsh, and sh respectively.

Those three functions 'HelloFromXyz' are all 3 supposed to be defined like this:
function HelloFromBash { echo "Hello $1, this is Bash speaking" }
and similar for the zsh and sh variants.

But the thing is: I want want to define these functions globally, one for each particular shell.

How or where do I define global functions for these three shells? So that when I run the three scripts above, they can each use the particular global function for that shell.

If there is one, uniform way to define (or export, or whatever the appropriate term is) global functions for multiple shells simultaneously, that's even better. But I believe this is not the case, each shell seems to use its own mechanism.

(edit) I understand there may be differences whether it's an interactive shell and/or a login shell or not. I would want the function to be available in shell scripts in all cases. So I can open a terminal manually, and run a script which uses said global function. Or I can run a background process which invokes the same shell scripts.
If that requires defining or exporting the same function in multiple files, or including/sourcing one in another, I'd love to learn the details.

RocketNuts
  • 1,342

1 Answers1

2

If you want to define a "library" of function to use in your scripts, write them in a file that you "source" in the script that use the function:

"Library" file:

function the_function {
    # whatever
}

Usage:

# include the library
source /path/to/the/library # You can also use ". /path/to/the/library"

# Or, of caller and library are in the same directory
source $(dirname "$0")/library 

# Call the function in it
the_function arg1 arg2

The library file doesn't need to be executable not does it need a shebang so it can be used by bash and ksh (and perhaps zsh) if coded adequately.

xenoid
  • 10,597