Bash – Include a bash function into the parent script

bashfunctionshell

I can to define function in bash and use it:

foo() { echo $1; }
foo test

But if I want to collect my functions in one bash script all its unavailable:

init.bash

#!/bin/bash
foo() { echo $1; }  
export -f foo # This not helps

Using:

./init.bash && foo test # error here

Is there any way to export script's functions to parent scope?
Without writing to .bashrc, it's too global
Same as .bashrc but for current bash instance only…

Best Answer

You could source the file init.sh. No need to export the function in that file.

$ cat init.bash 
foo() { echo $1; }

And use it:

$ . ./init.bash && foo test
test

Sourcing a file would execute commands from it in the current shell context. As such, the functions would be available in the parent.

export would set the attribute for a variable that would be applicable for the current shell and subshells. Not the parent shell. You need to define the variable in the current shell context.