Fibonacci in BASH
So here’s the big surprise. Shell scripting! It’s not what most people think of when they think of programming, but systems administrators are still doing lots of scripting work to automate tasks. Shell scripting can tackle some pretty serious and complicated problems, so running our Fibonacci program is no sweat. If you haven’t seen the Fibonacci in C and the Fibonacci in PHP, now might be a good time to review them.
#!/bin/bash # # Here is our main function. Like PHP, I could have simply placed this in the script # rather than having a function. You notice that like C and PHP, the printf function # still exists. Unlike C and PHP function calls do not enclose the parameters with # paraenthsis. function main { printf "\nHow many numbers of the sequence would you like?\n" # Bash lets us use a function "read" to get input from stdin # Notice that we are not using a dollar sign in front of the variables when # we set them, but we need to when we use them. read n fibonacci $n # Again, I'm exiting with status 0 exit 0 } # Starting to look familiar? This function is actually a little different than the # C style for loop that we've used before. Instead we use while..do..done to accomplish # the same thing. You'll also see that rather than specifying parameters in the # function;s declaration, we simply reference the variable "$1" to get the first parameter # passed when the function was called. function fibonacci { a=0 b=1 i=0 while [ $i -lt $1 ] do printf "%d\n" $a let sum=$a+$b let a=$b let b=$sum let i=$i+1 done } main
HTML code generated by vim-color-improved v.0.4.0.Download this code: fibonacci.sh
So what are the gotchas for scripting in BASH? What killed me is whitespace! (a=1 is not the same as a = 1). Once you get the hang of it, it’s not a big deal, but if you are used to working in PHP or another language that ignores whitespace, you’ll run through a few syntax errors before figuring it out. Using an editor like Vim that has syntax highlighting will help a lot there.So there is the third version of our Fibonacci project. Coming soon, I’ll take on the popular scripting languages perl, python, and ruby.