Floating-Point Math and the bc Utility
Have you ever needed to do some floating-point math in a shell script? If the answer is yes, then you' in luck. On UNIX machines there is an interactive program called bc that is an interpreter for the arbitrary-precision arithmetic language. You can start an interactive session by typing bc on the command line. Once in the session you can enter most complex arithmetic expressions as you would in a calculator. The bc utility can handle more than I can cover in this chapter, so we are going to keep the scope limited to simple floating-point math in shell scripts.
In this chapter we are going to create shell scripts that add, subtract, multiply, divide, and average a list of numbers. With each of these shell scripts the user has the option of specifying a scale, which is the number of significant digits to the right of the decimal point. If no scale is specified, an integer value is given in the result. Because the bc utility is an interactive program, we are going to use a here document to supply input to the interactive bc program. We cover using a here document in detail throughout this chapter. Of course, we can write an expect script to handle the automation. Sounds like a good Lab Assignment.
By now you know the routine: We need to know the syntax before we can create a shell script. Depending on what we are doing we need to create a mathematical statement to present to bc for a here document to work. A here document works ...