Chapter 6. Shell Logic and Arithmetic

One of the big improvements that modern versions of bash have when 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 can be used for so many tasks despite that awful mechanism for arithmetic. Maybe no one expected the shell to be so useful and so well used but, after a while, the simple counting useful for automating repetitive tasks needed simple, straightforward syntax. The lack of such capability in the original Bourne shell contributed to the success of the C shell (csh) when it introduced C Language-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. There are while loops and for loops, but 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.

Get bash Cookbook 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.