I have this Fibonacci script
#!/bin/bash
if (test $# -ne 1) then
echo "Use: $0 number"
exit 1 fi
for c in ‘seq 1 $1‘
do
if (($c == 1))
then
n0=1;
echo "fibonacci(1)=$n0";
elif (($c == 2));
then
n1=1;
echo "fibonacci(2)=$n1";
else
n=$(($n0+$n1));
echo "fibonacci($c)=$n";
n0=$n1;
n1=$n;
fi done
type here
I have to made a substitution of the expression evaluation $(($n0+$n1))with the shell command expr $n0 + $n1.
I Rembember that to assign the output of a command to a varible i have to made command > output.txt but I don’t know how to apply it on this exercise. Thank you so much for your help.
I think it's important to state up front: expr
is not needed for arithmetic in virtually any shell. Continue using n=$(( $n0 + $n1 ))
in practice.
That said, arithmetic was previously not supported by shells directly, and instead you used the expr
command. It accepted an expression as a series of arguments, and wrote the result to standard output. You capture standard output using the $( ... )
construct (similar to arithmetic expressions, but with one pair of parentheses instead of two).
# n=$(($n0 + $n1))
n=$( expr "$n0" + "$n1" )
Note that the number of arguments is important; expr 3 + 5
outputs 8
, but expr "3 + 5"
outputs 3 + 5
.