# Fibonacci numbers with awk

awk 'func f(n){return(n<2?n:f(n-1)+f(n-2))}BEGIN{while(a<24){print f(a++)}}'
recursive version, "pure" AWK
Sample Output
```0
1
1
2
3
5
8
13
21
34
55
89
144
233
377
610
987
1597
2584
4181
6765
10946
17711
28657```

5
2010-11-24 10:40:08

## 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
• 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

• 0
prev=0;next=1;echo \$prev;while(true);do echo \$next;sum=\$((\$prev+\$next));prev=\$next;next=\$sum;sleep 1;done
· 2009-09-06 09:38:10
• 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

Recursion: Pretty much always the wrong way to do something. Unless you're using a compiler on it before you run it, it will almost certainly be massively slower than a loop that does the same thing. Even with a compiler it's not a certainty you'll achieve comparable speeds. This, for instance, is 30x slower than http://www.commandlinefu.com/commands/view/1654/fibonacci-numbers-with-awk
TheMightyBuzzard · 478 weeks ago
who cares? It's elegant. If you really need speed you know where to find a C compiler ;-)
unefunge · 478 weeks 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.