How does Bash initialize local variables? Will the following commands always do the same thing (when used inside a function)?
local foo
local foo=
local foo=""
How does Bash initialize local variables? Will the following commands always do the same thing (when used inside a function)?
local foo
local foo=
local foo=""
local foo=""
and local foo=
are exactly equivalent. In both cases, the right-hand side of the equal sign is an empty string.
local foo
and local foo=
are different: local foo
leaves foo
unset while local foo=
sets foo
to an empty string. More precisely, local foo
creates a local variable, and that variable is initially unset. A subsequent assignment foo=…
sets the local value, and that assignment can be combined with the local
statement. Witness:
bash-4.3$ demo () {
local unset empty=
echo "unset=\"${unset-(not set)}\" empty=\"${empty-(not set)}\""
}
bash-4.3$ demo
unset="(not set)" empty=""
This is the same behavior as ksh (except that in ksh you need to use the keyword typeset
instead of local
). On the other hand, in zsh, local foo
sets foo
to an empty string.
local x=5
in your function, and then a local x
in the same function, x would still be 5.
– user1934428
Aug 29 '17 at 4:31