Using Ubuntu 18.04. My .bashrc file includes the lines:
if [ -f ~/.bash_usr_functions ]; then
. ~/.bash_usr_functions
fi
In .bash_usr_functions, there are a bunch of user-defined functions such as:
function MyAmazingFunc()
{
echo 1st param: $1
echo Function body is complex...omitted for brevity
}
Now whenever a new Linux Terminal is started, typing MyAmazingFunc 37 works as expected. Great!
Now I write a new bash script. This script would like to know about and use AmazingFunc. I had expected this to be automatic with this code:
#!/bin/bash
AmazingFunc 37
but when I run this using bash ./NewScript.sh there is an error: Command 'MyAmazingFunc' not found.
So, I modified NewScript.sh to include the same lines from .bashrc:
if [ -f ~/.bash_usr_functions ]; then
. ~/.bash_usr_functions
fi
This appears to work, but is very inelegant. Sourcing .bash_usr_functions actually launches a new, child bash process and runs any code in .bash_usr_functions! This can be verified by putting something like echo Hello from user functions or read VAR1 in that file.
Is there a better method to include your own user functions in a codebase (ie. many scripts) without having to copy the entire function into every bash script or use source?