Reputation: 1609
I am trying to source specific function of a bash file. Please find below simplified loadfun.sh :-
function a(){
echo "This is a"
}
function b(){
echo "This is b"
}
function load(){
echo "exporting $1"
export -f $1
}
$@
Also, please find below execution sequence of commands :-
$cat loadfun.sh
function a(){
echo "This is a"
}
function b(){
echo "This is b"
}
function load(){
echo "exporting $1"
export -f $1
}
$@
$
$
$
$sh loadfun.sh a
This is a
$
$
$a
bash: a: command not found
$
$
$sh loadfun.sh load a
exporting a
$
$
$
$a
bash: a: command not found
$
I am not sure why
export -f a
is not exporting function a.
Upvotes: 1
Views: 1281
Reputation: 295315
Source your script rather than executing it, so that the definitions and the export
take place in your current shell:
source loadfun.sh a
As an aside -- the .sh
extension is misleading; since this uses bash-only functionality, it should be named loadfun.bash
. (Using extensions is frowned on in general for executable scripts, but since this is intended to be loaded as a library, an extension is appropriate).
Upvotes: 0
Reputation: 11216
If you only want to set specific functions whilst sourcing the file then you could use a case statement
case $1 in
a)
a(){
echo "This is a"
}
;;
b)
b(){
echo "This is b"
}
;;
*)
echo error message
;;
esac
And call the script with
. ./script [function to export]
Upvotes: 1