Results 1 to 7 of 7
I am writing a script that outputs the fibanocci sequence and gives as many terms as specified by the argument.
#!/bin/sh
clear
i=0
a=0
b=0
echo "this is i $1"
...
- 11-02-2009 #1Just Joined!
- Join Date
- Oct 2009
- Posts
- 10
arithmatic in shell script
I am writing a script that outputs the fibanocci sequence and gives as many terms as specified by the argument.
#!/bin/sh
clear
i=0
a=0
b=0
echo "this is i $1"
while [ `expr $i` -lt `expr $1` ]
do
c=`expr $a+$b`
echo " $c"
a=$b
b=$c
i=`expr $i+1`
done
The error I get is this is i 6
0+0
./Fibanocci.sh: line 7: [: 0+1: integer expression expected
I'm guessing the problem is that arguments are automatically a string type so that's why I have the `expr`s inside the while loop.
- 11-03-2009 #2
Try this syntax:
Code:#!/bin/sh clear i=0 a=0 b=0 echo "this is i $1" while [ $i -lt $1 ] do c=$(($a+$b)) echo " $c" a=$b b=$c i=$(($i+1)) done
Men occasionally stumble over the truth,
but most of them pick themselves up
and hurry off as if nothing had happened.
Winston Churchill
... then the Unix-Gods created "man" ...
- 11-03-2009 #3Linux User
- Join Date
- May 2008
- Location
- NYC, moved from KS & MO
- Posts
- 251
You can't start a fibanocci with two 0's.
Code:#!/bin/bash [ $# -lt 1 ] && echo Usage: $0 count && exit 0 a=0 b=1 echo -n $a $b for i in `seq 1 $1`; do c=$((a+b)) echo -n " "$c a=$b b=$c done echo
- 11-03-2009 #4Just Joined!
- Join Date
- Oct 2009
- Posts
- 10
thanks that did it.
why was using expr wrong and what happens when you put the expression in $(...) ?
- 11-03-2009 #5Linux User
- Join Date
- May 2008
- Location
- NYC, moved from KS & MO
- Posts
- 251
For now you don't have to worry about type conversion in bash, types are automatically decided unless you specify (declare) otherwise. For example:
Regarding $((..)), please read Arithmetic ExpansionCode:$ a=3 $ b="4" $ [ $a -lt $b ] && echo yes yes
- 11-03-2009 #6Linux Newbie
- Join Date
- Mar 2009
- Posts
- 228
- 11-03-2009 #7
bc - An arbitrary precision calculator language
you can also try to have a look at the bc "command"
an example usage from a script:
Code:percent=`echo "100 * $counter / $total_lines" | bc -l` # calculate percent


Reply With Quote

