Sandra Schlichting
Sandra Schlichting

Reputation: 25986

Modify global variable from loop

Why do I get

/tmp/test: line 4: 0=Done: command not found

from the below

a="0"

while [ true ]; do
  $a="Done"
  exit
done

echo $a

I were expecting it would output Done.

Upvotes: 0

Views: 66

Answers (1)

Lix
Lix

Reputation: 47956

You don't need to use the $ when defining a variable, only when you are accessing it.

You'll need to change the line defining the variable a to:

a="Done"

As to an explanation, what I believe is happening here is that $a is being resolved to 0 and then the shell is seeing the entire 0=Done as a single (unfound) command. Accessing undefined variables still returns a 0 exit code.

Upvotes: 3

Related Questions