Chapter 6. Variables, Making Decisions, and Repeating Actions
Variables are essential for nontrivial programs. They maintain values useful as data and for managing program state. Since the shell is mostly a string processing language, there are lots of things you can do with the string values of shell variables. However, because mathematical operations are essential too, the POSIX shell also provides a mechanism for doing arithmetic with shell variables.
Control-flow features make a programming language: it's almost impossible to get any real work done if all you have are imperative statements. This chapter covers the shell's facilities for testing results, and making decisions based on those results, as well as looping.
Finally, functions let you group task-related statements in one place, making it easier to perform that task from multiple points within your script.
Variables and Arithmetic
Shell variables are like variables in any conventional programming language. They hold values until you need them. We described the basics of shell variable names and values in Section 2.5.2. In addition, shell scripts and functions have positional parameters, which is a fancy term for "command-line arguments."
Simple arithmetic operations are common in shell scripts; e.g.,
adding one to a variable each time around a loop. The POSIX shell
provides a notation for inline arithmetic called arithmetic expansion. The shell
evaluates arithmetic expressions inside $((
...))
, and places the result back ...
Get Classic Shell Scripting 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.