I have a script that can be sourced in bash or ksh or it runs in bash if executed. The script stores a desired return code in ${_rc}. I can return $_rc but that leaves _rc defined in the tty. I can unset _rc afterward but that overrides the return code. If the script is not sourced I need to use exit instead of return or i get an error message
I have the following code at the end of my script
cleanup_script # unsets all variables except _rc and _was_sourced
if [ "${_was_sourced}" == 1 ];
return ${_rc}
else
exit ${_rc}
fi
If I run this command
typeset > before.txt
. ./myscript
echo $?
typeset > after.txt
diff before.txt after.txt
I get (in addition to variables and functions defined by the script that I want available to the terminal)
226a236
> _rc=0
232a243
> _was_sourced=1
Which I desire to not have if possible
Just:
eval "unset _rc; return $_rc"
You could use this, to inject the _rc value before unsetting it
_rc=42
{
unset _rc
return "$(cat)"
} <<< "${_rc}"
Or as oneliner
{ unset _rc; return "$(cat)"; } <<< "${_rc}"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With