usually, see questions people not being able access variables outside scope. however, seem experiencing opposite: seeing variables still having values inner scopes should have given afterwards. example (making svn aliases similar git aliases):
function svn() { case $@ in alias*) shift 1; in "$@"; if [[ "$i" == "-t" ]]; j="$i,$j" elif [[ "$i" == "-f" ]]; k="$i,$j" fi done echo "i = $i" echo "j = $j" echo "k = $k" ;; esac }
i put in script , source it, function made alias bash (i think). try running various combinations of "-t" , "-f", , you'll see variables "$i", "$j", , "$k" keep values when running script again, , stay same in outer shell, after script has exited. using ubuntu 15.04 laptop, , when type ctrl-x
ctrl-v
shell outputs gnu bash, version 4.3.30(1)-release (x86_64-pc-linux-gnu).
everything have read bash tells me should not happen (admittedly, of beginner in area). variables should not stay set after script (or function) exits, unless use export
on them, have not. why happening?
there 2 different phenomena in play:
when variables exported, copied environments of child processes. non-exported variables not passed on. variables aren't exported unless explicitly use
export
mark them export.export less_options=-r # export `less` sees variable less
don't confuse scope, different.
inside functions variables have global scope default. have use
local
keyword declare local variables. otherwise loopfor in "$@"
modify global variable$i
rather creating local variable.svn() { local j k case $@ in ... esac }
exporting determines child processes see. scope determines whether functions modify global variables or not.
Comments
Post a Comment