Alexander Mills
Alexander Mills

Reputation: 100386

Does a local variable stay local if it's reassigned?

Say I have this in a bash function

ql_do_x(){
   local foo="bar";
   if true; then
      foo="zam";
   fi
}

If I run:

foo="unmodified"
ql_do_x
echo "$foo"

...is it guaranteed that the outer value of foo will be "unmodified", even though the local keyword was only used on the first assignment in the function and not the second one?

Upvotes: 2

Views: 1303

Answers (1)

Charles Duffy
Charles Duffy

Reputation: 295815

Absolutely, yes. In fact, it's better if you rely on this, and declare your variables prior to their assignment. Consider the following (not-very-unusual) example, where the value being assigned is coming from a command substitution, and where we want to handle the case where that command substitution fails:

ql_do_x() {
  local foo
  if ! foo=$(bar); then
    foo=baz
  fi
}

If you ran if ! local foo=$(bar), then it would always be true (before the !), because you'd be testing the exit status of local (which, as a command, has an exit status -- which is always true if the variable name(s) provided are valid), not the command substitution running bar.

Upvotes: 6

Related Questions