bashksh

In a sourced shell script set $? to a variable's value and then unset variable at same time


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


Solution

  • Just:

    eval "unset _rc; return $_rc"