1

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?

1
  • Sourcing does not launch a child process. It reads the sourced file in the current shell process. Commented Nov 2, 2019 at 1:27

3 Answers 3

3

Add this to your ~/.bashrc to export your function to the environment of subsequently executed commands:

export -f MyAmazingFunc

See: help export

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

1 Comment

Great, that works. Added it to the .bash_usr_functions file (just below the definition of MyAmazingFunc).
1

Note that '.bashrc' is only executed for 'interactive shell' - login shell, or when using (-i). If you want to be able to run your 'NewScript.sh' in other context, consider alternative implementing using 'include guard'. This will remove the dependency on the login shell.

In NewScript.sh

[ "$user_functions_loaded" ] || source ~/.bash_usr_functions

In ~/.bash_usr_functions

user_functions_loaded=1
func AmazingFunc ...

This approach eliminate the need to export individual functions - recall that if 'MyAmazingFunc' is calling other functions in ~/.bash_usr_functions, those will also have to be exported

Comments

0

Perhaps you can use BASH_ENV!
Try to add this line in your .xsessionrc file.

export BASH_ENV="$HOME/.bash_usr_functions"

Comments

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.