From https://unix.stackexchange.com/a/381782/674
For instance:
integer() { typeset -gi "$1"; }
To make a variable an integer works in
mksh
/yash
/zsh
. It works inbash
only on variables that have not been declared local by the caller:$ bash -c 'f() { declare a; integer a; a=1+1; echo "$a"; }; integer() { typeset -gi "$1"; }; f' 1+1 $ bash -c 'f() { integer a; a=1+1; echo "$a"; }; integer() { typeset -gi "$1"; }; f' 2
Note that
export var
is neithertypeset -x var
nortypeset -gx var
. It adds theexport
attribute without declaring a new variable if the variable already existed. Same forreadonly
vstypeset -r
.
For bash,
inside
f
of the first example, what doesinteger a
do, to declare a differenta
from thea
declared insidef
or to make thea
declared insidef
have the global scope? Why does it output1+1
?inside
f
of the second example, doesinteger a
declarea
with the global scope? Why does it output2
?
For zsh, the same questions, except that why the first example outputs 2
instead of 1+1
as for bash?
Am I correct that
- both bash and zsh use dynamic scoping, at least in the examples?
- the option
-g
oftypeset
in both bash and zsh means to declare a nonexisting variable with the global scope, or to change an existing variable to have the global scope?
Thanks.
typeset -gi var
does not give the integer attribute to var without instantiating it in the local scope"? I have been stuck at that sentence. – Tim Jul 28 '17 at 18:48