linux - 语法错误 : operand expected when using Bash

标签 linux bash for-loop

我有两个要循环的数组。我正确地构造了它们,在进入 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/

相关文章:

带有 While 循环的 Javascript 贷款计算器

C++11 基于范围的 for 循环 : how to ignore value?

linux - 使用 cronjob 和电子邮件创建短信 "server"

linux - 模拟 Linux/UNIX 中的 COM 编程

Node.js Unix 套接字不回显

bash - 为什么 "if $(ps aux | grep ...)"在 Bash 中总是成功?

c - 在 for 循环 C 中使用 fork() 时出现奇怪的输出

linux - 为什么 linux 重定向会截断文件?

git - 如何在带有别名的gitconfig中正确使用bash变量

for-loop - 如何处理迭代器的类型?