Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reuse a function defined in another bash file?

Tags:

linux

bash

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.

like image 235
AlikElzin-kilaka Avatar asked Nov 15 '25 17:11

AlikElzin-kilaka


1 Answers

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.

like image 198
bufh Avatar answered Nov 17 '25 08:11

bufh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!