Consider these 2 scripts:
envSetter.sh:
#!/bin/bash
export ENV_VAR=6
return 3
sourceable.sh:
#!/bin/bash
function main()
{
local var=5
source envSetter.sh
}
main "$@"
unset -f main
envSetter.sh is a script that sets some variables (and possibly performs other actions that affect the current shell (environment)). I need to create a sourceable script that will source envSetter.sh but will also clean up after itself. I.e. after running source sourceable.sh I want my shell to have ENV_VAR set but I don't want to have main (or anything else that sourceable.sh uses) defined.
The above scripts achieve that. However, on top of all that I want sourceable.sh to be able to return whatever exit code main returns. Right now the script returns the result of unset -f main. If I remove that command my script will leave main function defined which I don't want. If I try to use a temporary variable:
main "$@"
result=$?
unset -f main
return $result
It will return what I expect but will also leave result defined which I don't want. I could also not use a main function at all and put all the code in the top level of the script but that would expose even more garbage from inside main (e.g. local var) which I also don't want.
Is there a way to source envSetter.sh (i.e. let it set variables in the current shell), return whatever main returns and not "pollute" my current shell with anything sourceable.sh uses? To clarify: I want envSetter.sh to affect my current shell but I don't want sourceable.sh to.