# Fibonacci numbers with sh

prev=0;next=1;echo \$prev;while(true);do echo \$next;sum=\$((\$prev+\$next));prev=\$next;next=\$sum;sleep 1;done

0
2009-09-06 09:38:10

## 4 Alternatives + Submit Alt

• Another combination of seq and awk. Not very efficient, but sufficiently quick. Show Sample Output

14
seq 50| awk 'BEGIN {a=1; b=1} {print a; c=a+b; a=b; b=c}'
· 2009-03-24 20:39:24
• recursive version, "pure" AWK Show Sample Output

5
awk 'func f(n){return(n<2?n:f(n-1)+f(n-2))}BEGIN{while(a<24){print f(a++)}}'
· 2010-11-24 10:40:08
• Does not require input to function or complete. Number of iterations controlled by shell variable \$NUM. Show Sample Output

0
awk 'BEGIN {a=1;b=1;for(i=0;i<'\${NUM}';i++){print a;c=a+b;a=b;b=c}}'
· 2009-09-06 03:05:55
• only take the first field on each row to compute the fibo on this number Show Sample Output

-5
gawk '{n=\$1;a=0;b=1;c=1;for(i=1;i<n;i++){c=a+b;a=b;b=c};print c}' << eof
· 2010-11-26 08:36:30

### What Others Think

A variant of the bash solution that should work with all Bourne descendants that have \$(( )) arithmetic evaluation: `a=1;b=1;for i in \$(seq 1 40);do echo \$a;h=\$((a+b));a=\$b;b=\$h;done` Note that the shell's integers overflow rather quickly.
penpen · 534 weeks and 5 days ago

### What do you think?

Any thoughts on this command? Does it work on your machine? Can you do the same thing with only 14 characters?

You must be signed in to comment.

### What's this?

commandlinefu.com is the place to record those command-line gems that you return to again and again. That way others can gain from your CLI wisdom and you from theirs too. All commands can be commented on, discussed and voted up or down.

### Stay in the loop…

Follow the Tweets.

Every new command is wrapped in a tweet and posted to Twitter. Following the stream is a great way of staying abreast of the latest commands. For the more discerning, there are Twitter accounts for commands that get a minimum of 3 and 10 votes - that way only the great commands get tweeted.

Subscribe to the feeds.

Use your favourite RSS aggregator to stay in touch with the latest commands. There are feeds mirroring the 3 Twitter streams as well as for virtually every other subset (users, tags, functions,…):

Subscribe to the feed for: