4

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.

0

2 Answers 2

14

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

Good idea, but be careful as they wont be available from another script (ie: one of your crontab or a remote ssh) since your .bashrc is sourced only when your shell run in interactive mode and .profile when run by login.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.