Reputation: 35991
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.
Upvotes: 4
Views: 3579
Reputation: 67037
If you don't want to do an explicit sourcing of your script file as bufh suggests: I put my often used functions in my .bashrc
which gets always sourced thus having the functions always available.
As bufh pointed out in a comment always is not really always but limited to interactive shells. So, if you're planning to use the scripts from an interactive session, you could put it into the .bashrc
, otherwise go for explicit sourcing.
Upvotes: 0
Reputation: 3410
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
.
Upvotes: 14