linux – 语法错误:使用Bash时预期的操作数

我有两个我想要循环的数组.我正确地构造它们,然后在进入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循环中的变量被正确回显,但循环不起作用..我在哪里错了?

#

正如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循环是否完全符合你的要求……难道你的意思不是这样吗?

#!/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

相关文章

用的openwrt路由器,家里宽带申请了动态公网ip,为了方便把2...
#!/bin/bashcommand1&command2&wait从Shell脚本并行...
1.先查出MAMP下面集成的PHP版本cd/Applications/MAMP/bin/ph...
1、先输入locale-a,查看一下现在已安装的语言2、若不存在如...
BashPerlTclsyntaxdiff1.进制数表示Languagebinaryoctalhexa...
正常安装了k8s后,使用kubect工具后接的命令不能直接tab补全...