如何在bash中为变量赋值数组长度

Dor*_*ian 2 bash

我正在尝试编写一个简单的bash脚本,它可以添加整数并提供总和.我认为最简单的方法是将输入分配给数组.然后遍历数组以执行求和.我需要在for循环中使用数组的长度,并且无法弄清楚如何将数组长度分配给变量.

任何帮助在简单的脚本(我做了学习bash)上表示赞赏

#!/bin/bash
# add1 : adding user supplied ints

echo -n "Please enter any number of integers: "
read -a input

echo "Your input is ${input[*]}"
echo "${#input[@]} number of elements"

num = ${#input[@]}   # causing error
for ((i = 0; i < "${num}"; ++i )); do  # causing error
  sum = $((sum + input[$i]))
done

echo "The sum of your input is $sum"
Run Code Online (Sandbox Code Playgroud)

这会产生错误:

line 10: num: command not found 
line 11: ((: i < :syntax error: operand expected (error token is "< ")
Run Code Online (Sandbox Code Playgroud)

hek*_*mgl 8

你只是有一个语法错误.删除之前的空格=:

num = ${#input[@]}   # causing error
Run Code Online (Sandbox Code Playgroud)

变为:

num=${#input[@]}   # works
Run Code Online (Sandbox Code Playgroud)

请注意,如果使用=运算符分配给bash中的变量,则之前和之后不得有任何空格=

请阅读"高级Bash脚本编制指南"中有关"变量分配"的此条目