I would like your opinion on my shell script that prints the Fibonacci sequence.
#!/bin/bash
first=0
second=1
third=1
echo -n "Term: "
read term
fub=$((second+third))
echo $second
echo $third
echo $fub
for ((i=1; i<term; i++))
do
third=$((fub+third))
echo $third
fub=$((third+fub))
echo $fub
done
I tried to calculate the Fibonacci sequence in the simplest way (without the use of recursive functions).
-
\$\begingroup\$ Just so you know, bash is extremely inefficient for this type of usage. If you want to change system settings, install software, or generally handle anything to do with files, use bash. For computational/algorithmic type problems, not so much. As someone (Xanthir) on the xkcd forums wrote, "The correct way to write anything in Bash is to write it in ANY OTHER LANGUAGE, then call it from a bash script." Which is crude but accurate for computational/algorithmic type problems. \$\endgroup\$Wildcard– Wildcard2015年10月15日 03:52:05 +00:00Commented Oct 15, 2015 at 3:52
-
\$\begingroup\$ Yeah, I understand that. BASH is not granular enough for specific mathematical logic. \$\endgroup\$Bruce Blacklaws– Bruce Blacklaws2015年11月03日 12:38:43 +00:00Commented Nov 3, 2015 at 12:38
2 Answers 2
What does "Term" mean? I'd prefer to see 5 numbers if the user entered 5.
#!/bin/bash
echo -n 'Term: '
read term
i=0
j=1
for (( c=0; c<term; c++ )) ; do
(( n=i+j ))
(( i=j ))
(( j=n ))
echo $i
done
-
\$\begingroup\$ Looks like terminal, terminate or something like that. end then. \$\endgroup\$Mingye Wang– Mingye Wang2015年10月25日 23:07:03 +00:00Commented Oct 25, 2015 at 23:07
While I don't write in Bash, I do know that you don't need more than two variables, at the most, to compute the Fibonacci sequence. In fact, you're very close to doing so.
Just sort of manipulating your code here,
#!/bin/bash
# first was never used, it was not required
second=1 # Somewhat confusing name, consider something different
third=1 # Same here.
echo -n "Term: "
read -r term # Using the -r argument was recommended after research
# Notice this functions without the beginning section
for ((i=1; i<term; i++))
do
echo $second
second=$((second+third))
echo $third
third=$((second+third))
done
If you were to apply this code to your picture above, simply replace all instances of fub
with second
.
Edit:
The modified code should display 2*term-2 numbers
, (Your code as it is now displays more, 2*term+1
numbers)
To change this so it only displays term
numbers, change term
so it's the proper upper limit after you've read it.
So, the code could look something like this:
for ((i=1; i<term/2+1; i++))
Tested it and yes, the code does work.