Chapter 6. Shell Logic and Arithmetic

One of the big improvements in modern versions of bash compared with the original Bourne shell is in the area of arithmetic. Early versions of the shell had no built-in arithmetic; it had to be done by invoking a separate executable, even just to add 1 to a variable. In a way it’s a tribute to how useful and powerful the shell was (and is) that it could be used for so many tasks despite that awful mechanism for arithmetic. After a while, though, it became clear that simple, straightforward syntax was needed for the simple counting useful for automating repetitive tasks. The lack of such capability in the original Bourne shell contributed to the success of the C shell (csh) when it introduced C-like syntax for shell programming, including numeric variables. Well, that was then and this is now. If you haven’t looked at shell arithmetic in bash for a while, you’re in for a big surprise.

Beyond arithmetic, there are the control structures familiar to any programmer. There is an if/then/else construct for decision making, as well as while loops and for loops, though you will see some bash peculiarities to all of these. There is a case statement made quite powerful by its string pattern matching, and an odd construct called select. After discussing these features, we will end the chapter by using them to build two simple command-line calculators.

6.1 Doing Arithmetic in Your Shell Script

Problem

You need to do some simple arithmetic in your shell ...

Get bash Cookbook, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.