# Fibonacci numbers with awk

awk 'BEGIN {a=1;b=1;for(i=0;i<'\${NUM}';i++){print a;c=a+b;a=b;b=c}}'
Does not require input to function or complete. Number of iterations controlled by shell variable \$NUM.
Sample Output
```1
1
2
3
5
8
13
21
34
55
89
144
233
377
610
987
1597
2584
4181
6765
10946
17711
28657```

0
2009-09-06 03:05:55

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

• 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

The Fibononacci sequence is supposed to start from 0, not 1.
sharfah · 551 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.