Unix Tip: More on bc

March 20, 2008, 10: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:

rivet> ./factorial
num> 111
176295255109024466387216104710707578876140953602656551604157406\
33473469550872483164365555745984623157731960476628379789131458474971\
99871623320096254145331200000000000000000000000000

The bc utility also includes a rudimentary form of test logic. If you type "12 > 6" in bc, for example, bc will respond with a "1", meaning "true"; Twelve is greater than 6. If you type "6 > 12" on the other hand, the response will be "0" for false. In a similar vein, you can use less than (<), less than or equal (<=), greater
than or equal (>=), equal (==) and not equal (!=). You can also calculate the reverse response, if for some reason you want to, by prepending a not (!) sign to your statement. For example:

!(6>12)
1

AND and OR operations are invoked with || and && operators as shown
in these examples:

(6>12)||(6>10)
0
(6>5)&&(6>3)
1

The bc utitity also has while and for statements. Here's a simple example of while statement:

while ( number > 0 ) {
  print number
  number=number-1
}
1110987654321

Here's a similar for statement:

for (number=11; number=number-1; number>0) {
    print number
    print "\n"
}
10
9
8
7
6
5
4
3
2
1

Some versions of bc also provide geometric functions, such as sine and cosine and natural logarithms.

There's a lot to this little language you are likely to find it handy whether you need to work in various numeric bases, handle extremely large numbers or do rapid fire numerical comparisons.

ITworld.com

I like it!
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.
Resources
White Paper

Symantec Backup Exec 12 and Backup Exec System Recovery 8 deliver industry leading Windows data protection and system recovery. Download this whitepaper to find out the top reasons to upgrade and how to get continuous data protection and complete system recovery.

Webcast

Data and system loss — from a hard drive failure, malicious attack, natural disaster, or simple human error — can happen anytime. Don’t leave your business vulnerable. Make sure you have a secure recovery strategy in place. Symantec's latest backup and system recovery technology can efficiently restore critical applications, individual emails and documents and even restore your entire system in minutes in the event of a loss.

White Paper

Businesses face a growing challenge to ensure that the IT environment is properly protected. Backup Exec 12 integrates with other applications in the Symantec family of products, to complement your current data protection strategy, keep your data securely backed up and make it recoverable when you need it most.

Free stuff

Crimeware: Understanding New Attacks and Defenses
By Markus Jakobsson, Zulfikar Ramzan
Published Apr 6, 2008 by Addison-Wesley Professional. Part of the Symantec Press series.
Enter now! | Official rules | Sample chapter

Securing VoIP Networks: Threats, Vulnerabilities, and Countermeasures
By Peter Thermos, Ari Takanen
Published Aug 1, 2007 by Addison-Wesley Professional.
Enter now! | Official rules | Sample chapter

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.

More Resources