0

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.

4
  • 2
    You should use break to exit a loop. exit will exit the whole shell. Commented May 8, 2018 at 11:10
  • Why you need a while [ true ] loop at all if you have an unconditional break or exit? Commented May 8, 2018 at 11:13
  • 1
    @Alfe That solved it. Could you post that as an answer? Commented May 8, 2018 at 12:02
  • 1
    Why test the string "true" when you could just execute the true command (i.e. while true; do ...; done). Not that there's any point in a loop with unconditional break, but... Commented May 8, 2018 at 13:02

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

If I do that, then it doesn't print anything. @Alfe's comment is the solition.
Yes this would have been the next issue :) My answer handles the error you reported in your original post.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.