我有两个要循环的数组。我正确地构造了它们,在进入 for 循环之前,我确实回显它们以确保数组一切正常。 但是当我运行脚本时,它会输出一个错误:
l<=: syntax error: operand expected (error token is "<="
我咨询了强大的谷歌,我知道它因缺少第二个变量而受到影响,但我之前提到过我确实回应了这些值,一切似乎都很好。这是片段..
#!/bin/bash
k=0
#this loop is just for being sure array is loaded
while [[ $k -le ${#hitEnd[@]} ]]
do
echo "hitEnd is: ${hitEnd[k]} and hitStart is: ${hitStart[k]}"
# here outputs the values correct
k=$((k+1))
done
k=0
for ((l=${hitStart[k]};l<=${hitEnd[k]};l++)) ; do //this is error line..
let array[l]++
k=$((k+1))
done
for 循环中的变量被正确回显,但 for 循环不起作用..我哪里错了?
#正如 gniourf_gniourf 回答的那样:
"... At some point, k will reach the value ${#hitEnd[@]}, and this is exactly when hitEnd[k] is not defined and expands to an empty string! Bang!"
意思是错误输出不是在循环开始时显示,而是当 k 的值大于数组的索引时,指向数组不包含的索引...
最佳答案
那是因为在某个时刻 ${hitEnd[k]}
扩展为空(未定义)。我得到与 ((l<=))
相同的错误.你应该写你的 for
循环为:
k=0
for ((l=${hitStart[0]};k<${#hitEnd[@]} && l<=${hitEnd[k]};l++)); do
以便始终有一个索引 k
对应于数组中定义的字段 ${hitEnd[@]}
.
另外,而不是
k=$((k+1))
你可以写
((++k))
完成!
您的脚本使用更好的现代 bash 实践进行了修改:
#!/bin/bash
k=0
#this loop is just for being sure array is loaded
while ((k<=${#hitEnd[@]})); do
echo "hitEnd is: ${hitEnd[k]} and hitStart is: ${hitStart[k]}"
# here outputs the values correct
((++k))
done
k=0
for ((l=hitStart[0];k<${#hitEnd[@]} && l<=hitEnd[k];++l)); do
((++array[l]))
((++k))
done
现在,我不太确定 for
loop 完全按照您的意愿执行...您不是这个意思吗?
#!/bin/bash
# define arrays hitStart[@] and hitEnd[@]...
# define array array[@]
#this loop is just for being sure array is loaded
for ((k=0;k<${#hitEnd[@]};++k)); do
echo "hitEnd is: ${hitEnd[k]} and hitStart is: ${hitStart[k]}"
# here outputs the values correct
((++k))
done
for ((k=0;k<${#hitEnd[@]};++k)); do
for ((l=hitStart[k];l<=hitEnd[k];++l)); do
((++array[l]))
done
done
关于linux - 语法错误 : operand expected when using Bash,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13672022/