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=""

1 Answer 1


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.

  • Not quite correct: The first form does not unset the variable. For example, if you have first a statement local x=5 in your function, and then a local x in the same function, x would still be 5. Commented Aug 29, 2017 at 4:31
  • I've noticed that any of these 3 ways to initialize make the -z, -n and -f completely equivalent in a test. foo always passes the tests unless initialized to something other than "".
    – sinekonata
    Commented Mar 3, 2019 at 10:14

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .