13

I am trying to get the array in the while-loop and need to update the value in array too.

Below is my code what I have tried. I get this error [0: command not found

#!/bin/bash i=0 while [$i -le "{#myarray[@]}" ] do echo "Welcome $i times" i= $(($i+1))) done 

How do I fix this?

1

1 Answer 1

32

Need a space after [ and no space before or after = in the assignment. $(($i+1))) would try to execute the output of the ((...)) expression and I am sure that's not what you want. Also, you are missing a $ before the array name.

With these things corrected, your while loop would be:

#!/bin/bash i=0 while [ "$i" -le "${#myarray[@]}" ] do echo "Welcome $i times" i=$((i + 1)) done 
  • i=$((i + 1)) can also be written as ((i++))
  • it is always better to enclose variables in double quotes inside [ ... ]
  • check your script through shellcheck - you can catch most basic issues there

See also:

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

2 Comments

Great answer to an iffy question (broad enough to be split into multiple dupes, as you've pointed out).
this was the only thing stopping my startup script from working in my .bashrc file, thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.