AlainD
AlainD

Reputation: 6607

Include common functions in multiple bash scripts

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?

Upvotes: 1

Views: 2462

Answers (3)

ctac_
ctac_

Reputation: 2471

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

export BASH_ENV="$HOME/.bash_usr_functions"

Upvotes: 0

dash-o
dash-o

Reputation: 14452

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

Upvotes: 1

Cyrus
Cyrus

Reputation: 88626

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

export -f MyAmazingFunc

See: help export

Upvotes: 3

Related Questions