我试着写一个简单的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"
这会导致错误:
line 10: num: command not found
line 11: ((: i < :syntax error: operand expected (error token is "< ")