我正在尝试在while循环中获取数组并需要更新数组中的值。
以下是我尝试过的代码。我遇到了这个错误 [0: command not found
#!/bin/bash
i=0
while [$i -le "{#myarray[@]}" ]
do
echo "Welcome $i times"
i= $(($i+1)))
done
我该如何修复这个问题?
我正在尝试在while循环中获取数组并需要更新数组中的值。
以下是我尝试过的代码。我遇到了这个错误 [0: command not found
#!/bin/bash
i=0
while [$i -le "{#myarray[@]}" ]
do
echo "Welcome $i times"
i= $(($i+1)))
done
我该如何修复这个问题?
[
后面加上一个空格,=
前后不要有空格。在$(($i+1)))
中,会尝试执行((...))
表达式的输出,我确定这不是你想要的。此外,在数组名之前缺少一个$
。
纠正这些问题后,您的while循环将如下所示:
#!/bin/bash
i=0
while [ "$i" -le "${#myarray[@]}" ]
do
echo "Welcome $i times"
i=$((i + 1))
done
i=$((i + 1))
可以写成 ((i++))
[ ... ]
中,将变量用双引号括起来总是更好的选择另请参阅: