Skip to content
Advertisement

How to reuse a function defined in another bash file?

I have a utility function that I used a lot (assertReturnStatus()). I’d like to define it in a utility file (utility.sh) and reuse it in other bash scripts.

How can reuse the function from another bash script file? Thanks.

Advertisement

Answer

You need to “import” the first file in the second.

Be warned that this will litterally include the first, so any code in the first will be executed as if it were litterally in the place of the line.

The syntax is:

# if /path/to/file exists, then include it
[ -f /path/to/file ] && . /path/to/file

Note bash also support the keyword source (ie: source /path/to/file) but it is not POSIX compliant and might not work in other shell like ash, dash, posh.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement