如何在 Shell 脚本中编写程序

How to code the program in the Shell Script

如何编写Shell脚本中的程序,用键盘输入的上限计算斐波那契数列的总和?输入例如:“输入斐波那契数列的极限?10”。结果:0 + 1 + 1 + 2 + 3 + 5 + 8 + 13 + 21 + 34 = 88

#!/bin/bash
if [ $# -eq 1 ]
then 
    Num=
else
    echo -n "Enter the limits of the Fibonacci sequence : "
    read Num
fi

a=0
b=1

echo "Result : "
for (( i=0;i<=Num;i++ ))
do
    echo -n “$a + “
    n=$((a+b))
    a=$b
    b=$n
done
echo

有人知道如何得到结果吗? 我的预期输出是:

Enter the limits of the Fibonacci sequence : 10
Result : 0 + 1 + 1 + 2 + 3 + 5 + 8 + 13 + 21 + 34 = 88

我一直在尝试

这个有效:

a=1; 
b=0; 
sum=$a; 
for ((i=1;i<10-1;++i)); do 
    ((tmp=b)); 
    ((b=a)); 
    ((a+=tmp)); 
    ((sum+=a)); 
done; 
echo $sum;

我终端的输出:

[ichramm@hypernova][Wed, 28 Oct 16:19:24][~]
$ a=1; b=0; sum=$a; for ((i=1;i<10-1;++i)); do ((tmp=b)); ((b=a)); ((a+=tmp)); ((sum+=a)); done; echo $sum;
88
$ cat fib
#!/bin/bash
Num=${1-5}
a=0
b=1
unset s

printf "Result: "
for (( i=0; i<Num; i++ )); do
    printf "${s:+ + }$a"
    s=$(($s + $a))
    n=$((a+$b))
    a=$b
    b=$n
done
echo " = $s"
$ ./fib 5
Result: 0 + 1 + 1 + 2 + 3 = 7
$ ./fib 10
Result: 0 + 1 + 1 + 2 + 3 + 5 + 8 + 13 + 21 + 34 = 88