【问题标题】:giving an array sum values in a for loop在 for 循环中给出数组总和值
【发布时间】:2018-09-04 23:20:44
【问题描述】:

我遇到了这个烦人的问题,连我的老师都解决不了:/. 我想用从 1 到 100 的总和值填充一个数组,这是我的代码:

while [ $i -le 100 ]
do
    #filling the list with the sums of i at the pos i
    sumList[$i]=$(echo $i | sum)
    echo $i |sum
    echo $sumList[$i]

    i=$(($i+1))
done

由于某种原因,它只是用第一个值 (00034 1) 填充所有点 我不知道该怎么办

【问题讨论】:

  • 和00034 1是0的和值
  • 什么是sum?而echo $sumList[$i] 应该是echo ${sumList[$i]}

标签: arrays linux bash for-loop sum


【解决方案1】:

这里是ShellCheck

Line 6:
    echo $sumList[$i]
         ^-- SC1087: Use braces when expanding arrays, e.g. ${array[idx]} (or ${var}[.. to quiet).
         ^-- SC2128: Expanding an array without an index only gives the first element.

有了这个固定:

i=1
while [ $i -le 100 ]
do
    #filling the list with the sums of i at the pos i
    sumList[$i]=$(echo $i | sum)
    echo $i |sum
    echo ${sumList[$i]}

    i=$(($i+1))
done

你会得到你所期望的所有不同的校验和和块计数:

32802     1
32802 1
00035     1
00035 1
32803     1
32803 1
00036     1
00036 1
32804     1
32804 1
[...]

【讨论】:

  • 在双圆括号内,变量名被解析,所以i=$(($i+1))应该是i=$((i+1))
【解决方案2】:

如果您实际检查该脚本的 输出(删除 echo $i |sum 行),那么发生的事情应该会很明显:​​

00034 1[0]
00034 1[1]
00034 1[2]
: : :
00034 1[100]

如您所见,echo $sumList[$i] 行给出了$sumList(与${sumList[0]} 相同)和$i 单独,这是因为,根据bash文档(我的重点):

可以使用${name[subscript]} 引用数组的任何元素。大括号是必需的以避免冲突...

因此,如果您将其更改为正确的 ${sumList[$i]}`,您会发现 确实正确设置了数组,只是没有打印它正确:

00034 1
32802 1
00035 1
: : :
08244 1

而且,就其价值而言,bash 中还有 其他 设施可以让你的代码更简洁,如果这是你的目标:

for i in {0..100}; do sumList[$i]="$(echo $i | sum)" ; done
IFS=$'\n' ; echo "${sumList[*]}"

【讨论】:

    猜你喜欢
    • 2019-07-07
    • 1970-01-01
    • 2021-06-07
    • 2017-12-16
    • 2018-08-08
    • 1970-01-01
    • 1970-01-01
    • 2023-03-03
    • 2021-05-18
    相关资源
    最近更新 更多