Using the expr Command
Theexpr command is a traditional way to perform arithmetic operations in shell scripts. To use it, simply provide an arithmetic expression as input, and it will output the result. For example, the following command adds two numbers:
Ensure that operators and operands are strictly separated by spaces. When multiplying using
expr, the star symbol (*) must be escaped with a backslash because * is interpreted as a reserved regex character.expr command supports other arithmetic operations like subtraction, division, and multiplication. You can also incorporate variable substitution. Consider the following examples:
Using Double Parentheses
Bash also offers a more concise method for arithmetic evaluation using double parentheses(( )). This C-like syntax automatically handles variable expansion (no need to prefix variables with $) and doesn’t require spaces between operators and operands. Escaping the multiplication operator is also unnecessary.
For example, the following commands perform arithmetic operations:
++A), pre-decrement (--A), post-increment (A++), and post-decrement (A--). Observe the following:
Always use
echo or store the result in a variable when using arithmetic expansion. Failing to do so might cause the shell to misinterpret the output as a command, leading to errors.Performing Floating Point Arithmetic with bc
Bothexpr and double parentheses support only integer arithmetic. To handle floating point calculations, use the bc utility. The bc tool acts as a basic calculator and is ideal for more precise computations.
For instance, dividing 10 by 3 using integer arithmetic returns an integer result:
-l flag with bc:
-l flag loads the standard math library, enabling accurate floating point calculations. You can interact with bc in a script or use piping for one-off operations.
Summary
By utilizing the methods discussed above, you can effectively perform both integer and floating point arithmetic in your shell scripts. Whether you choose the traditionalexpr command, the modern double parentheses expansion, or the versatile bc utility for precision arithmetic, these techniques are essential for automating numerical operations in your scripts.
Happy scripting!