"[0: command not found" in Bash

I am trying to get an array in a while loop, and I also need to update the value in the array.

Below is my code that I 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 can I fix this?

+7
source share
1 answer

Need a space after [and without a space before or after =in the destination. $(($i+1)))will try to execute the output of the expression ((...)), and I'm sure that is not what you need. Also, what you are missing is $before the array name.

After fixing these errors, your while loop will:

#!/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's always better to enclose variables in double quotes inside [ ... ]
  • shellcheck -

:

+14

Source: https://habr.com/ru/post/1671261/


All Articles