使用Bash时需要操作数

使用Bash时需要操作数

本文介绍了语法错误:使用Bash时需要操作数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个要循环的数组.我正确地构造了它们,在进入for循环之前,我确实回显了它们以确保一切都可以.但是当我运行脚本时,它会输出错误:

I have two arrays that I want to loop in. I construct those properly and before going into for loop, I do echo them to be sure everything is ok with arrays.But when I run the script, it outputs an error:

l<=: syntax error: operand expected (error token is "<="

我咨询了强大的Google,并了解它缺少第二个变量,但是我之前提到过,我确实回显了这些值,并且一切似乎都还可以.这是代码段..

I consulted the mighty Google and I understood it suffers from the lack of the second variable, but I mentioned earlier I do echo the values and everything seems to be OK. Here is the snippet..

#!/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循环将无法工作..我在哪里错了?

The variables in the for loop are echoed correctly but for loop won't work.. where am I wrong?

gniourf_gniourf回答:

as gniourf_gniourf answered:

表示错误输出不是在循环开始时显示,而是在k的值大于数组索引的值时,指向数组不包含的索引...

meaning error output is displayed not at the beginning of the loop, but when k has a greater value than array's indices, pointing an index that array does not include...

推荐答案

那是因为在某些时候${hitEnd[k]}扩展为空(未定义).我在((l<=))上遇到了相同的错误.您应该将for循环写为:

That's because at some point ${hitEnd[k]} expands to nothing (it is undefined). I get the same error with ((l<=)). You should write your for loop as:

k=0
for ((l=${hitStart[0]};k<${#hitEnd[@]} && l<=${hitEnd[k]};l++)); do

,以便始终具有与数组${hitEnd[@]}中定义的字段相对应的索引k.

so as to always have an index k that corresponds to a defined field in the array ${hitEnd[@]}.

也可以代替

k=$((k+1))

你可以写

((++k))

完成!

您的脚本使用了更好的现代bash练习进行了修订:

Your script revised using better modern bash practice:

#!/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循环是否确实可以实现您想要的功能……您不是这个意思吗?

Now, I'm not too sure the for loop does exactly what you want it to... Don't you mean this instead?

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

这篇关于语法错误:使用Bash时需要操作数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 02:11