Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

ksh

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

like image 897
guest Avatar asked Oct 22 '25 15:10

guest


2 Answers

Just:

eval "unset _rc; return $_rc"
like image 50
KamilCuk Avatar answered Oct 25 '25 04:10

KamilCuk


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}"
like image 26
jeb Avatar answered Oct 25 '25 04:10

jeb