3

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

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. – user1934428 Aug 29 '17 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 Mar 3 at 10:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.