Unix Tip: More on bc

March 20, 2008, 09:25 AM —  ITworld.com — 

In a previous column, we looked at bc, the surprisingly high precision and big value capable Unix tool that you will find on most versions of Unix today. The bc utility is not just a command line tool, however. You can also write numerically intensive scripts in bc. The tool incorporates enough syntax to assign values to variables, write and call functions, collect responses from users and print annotated results.

To start a bc script, you include the path to bc in your
shebang line as you would for any shell.

#!/usr/bin/bc

Let's look at a script for computing factorials. The mainpart of this script (the "f" function) comes straight from the man page. I've added a -q to the shebang line so that the script doesn't print the traditional bc welcome line, a prompt to nudge the user into providing some input, a read statement to collect the user's response, a call to the f function, a command to print the result and a quit command (otherwise, you will still be running bc when the script has ended.

#!/usr/bin/bc -q

/* factorial */
define f (x) {
  if (x <= 1) return (1);
  return (f(x-1) * x);
}

print "num> "
num=read()
ans=f(num)
print ans
print "\n"
quit

Notice that function f is recursive. Based on our understanding of factorials, each time the function calls itself, it does so with a decremented argument. If the user enters 3, for example, the function is called from the main body of the script with the argument 3 and the function then calls itself twice -- once with the number 2 and once with the number 1.

Notice the C-like comment on line 3 and the print newline statement on line 13. Like C and Perl, you need to request a newline if you want one. Even if you are using bc interactively, you will not get a newline unless you ask for one. Type "print 11" and your cursor will be sitting to the right of the printed number.

Probably the hardest thing to get used to is the lack of a prompt.You type "bc" on the command line and you will see something like this:

rivet> bc
bc 1.05
Copyright 1991, 1992, 1993, 1994, 1997, 1998 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'.

Your cursor then sits on a blank line while bc waits for your request.

If we follow the math through the script, we see that f(3) becomes f(2) * 3 which becomes f(1) * 2 * 3 which finally becomes 1 * 2 * 3 or 6.

If the user types in a large number, say 111 or 1234, the result is going to span multiple lines just as did many of the answers we looked at last week:

Sign up for ITworld's Daily newsletter
Follow ITworld on Twitter @IT_world

I like it!
Close

On Twitter now

unix

Powered by Twitter
You are logged in | Sign out
Sign in and post to Twitter

What are you thinking?

Cancel Tweet sent

On Twitter now

Post a comment
The content of this field is kept private and will not be shown publicly.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.
peer-to-peer

Esther Schindler
If the comments are ugly, the code is ugly

claird
SVG a graphics format for 21st century

pasmith
Take Chrome OS for a test spin

Sandra Henry-Stocker
Solaris Tip: Have Your Files Changed Since Installation?

sjvn
64-bits of protection?

jfruh
Android fragments vs. the iPhone monolith

mikelgan
What Gizmodo missed about the Pro WX Wireless USB disk drive

 

Where Google Chrome security fails: the password
I heard mention that the Chrome OS will have some sort of encryption available a la bitlocker. If it's possible to encrypt personal data using another password or key, then it may have potential for very secure data.... And Ubuntu has an 'encrypt home directory' option, perhaps google should follow suit.
- Dann

Join the conversation here

The Daily Tip

The Daily TipQuick, practical advice for IT pros. Made fresh daily.

Hot tips:

Want to cash in on your IT savvy? Send your tip to tips@itworld.com. If we post it, we'll send you a $25 Amazon e-gift card.

Newsletters

Subscribe to ITWORLD TODAY and receive the latest IT news and analysis.

I would like to receive offers via email from ITworld partners.
By clicking submit you agree to the terms and conditions outlined in ITworld's privacy policy.
Featured Sponsor

AISO founders envisioned a Web hosting company that was environmentally friendly. While the company employed energy-efficient innovations like solar panels, its infrastructure produced unacceptable power and cooling requirements. Find out how AISO leveraged AMD technology to overcome their challenge in this case study white paper.

In this whitepaper, Scalar explores the opportunity to change the landscape with respect to mission critical databases built around Oracle. Leveraging technologies such as Linux, high-end commodity processing power and Oracle RAC technology to architect, design, build and maintain database infrastructure that delivers maximum availability, reliability and performance at a fraction of traditional cost.

On a typical day, weather.com, the Web site for The Weather Channel in Atlanta, serves up between 15 million and 20 million page views. But in September 2004, when back-to-back hurricanes ransacked Florida, the peak traffic on one day more than tripled: over 70 million page views by more than 7 million unique visitors. Read the full success story now.

Marketplace