我必须编写一个带有参数n
的脚本,并创建一个大小为n
的表,其中填充了1,2,3,4,..,n。
我现在要显示所有案例的总和。
#!bin/bash
for i in $1 do
tab[i]=$i
echo "$tab[i]
done
答案 0 :(得分:1)
#!/bin/sh
if [ "$#" != 1 ]
then
echo $0 SIZE
exit
fi
# We can use one “for” loop to both fill the array, and calculate the sum.
for ((z=1; z<=$1; z++))
do
# Here we are creating our array “y” and adding a new value to it, “z”
y+=($z)
# Here we will use “let”. This is the same as using ((x+=z)), it is a way
# to perform arithmetic on variables. In this case we are adding “z”
# (current array value) to the total “x”
let x+=z
done
declare -p y x
输入
7
输出
declare -a y='([0]="1" [1]="2" [2]="3" [3]="4" [4]="5" [5]="6" [6]="7")'
declare -- x="28"
您可以调整输出,我只使用了declare
,因此您可以看到所有内容
清楚。