|
Shell scripting supports arithmetic operations through several mechanisms. This example covers the main ways to do math in shell scripts. POSIX arithmetic expansion with |
|
|
Output:
Basic arithmetic with $(( )): 5 + 3 = 8 10 - 4 = 6 6 * 7 = 42 20 / 4 = 5 17 % 5 = 2 |
|
|
Variables in arithmetic (no |
|
|
Output:
With variables (x=10, y=3): x + y = 13 x * y = 30 x / y = 3 x % y = 1 |
|
|
Compound assignment: |
|
|
Output:
After increment: count = 1 |
|
|
Bash
Bash provides shorter increment/decrement: |
|
|
Comparison operators (return 1 for true, 0 for false): |
|
|
Output:
Comparisons (a=5, b=10): a < b: 1 a > b: 0 a == b: 0 a != b: 1 a <= b: 1 a >= b: 0 |
|
|
Logical operators: |
|
|
Output:
Logical operators: 1 && 1 = 1 1 && 0 = 0 1 || 0 = 1 !0 = 1 !1 = 0 |
|
|
Bitwise operators: |
|
|
Output:
Bitwise operators: 5 & 3 = 1 5 | 3 = 7 5 ^ 3 = 6 ~5 = -6 4 << 2 = 16 16 >> 2 = 4 |
|
|
Ternary operator is a shorthand way to write an if-else statement. The syntax is: $((condition ? expression1 : expression2)) If the condition is true, the expression1 is evaluated and returned. Otherwise, the expression2 is evaluated and returned. This example shows how to use the ternary operator to find the maximum of two numbers. |
|
|
Output:
Max of 10 and 20: 20 |
|
|
Parentheses for grouping: |
|
|
Output:
Order of operations: 2 + 3 * 4 = 14 (2 + 3) * 4 = 20 |
|
|
Bash
Different bases: |
|
|
Output:
Different bases: Hex 0xFF = 255 Octal 077 = 63 Binary 2#1010 = 10 |
|
|
Using |
|
|
Output:
Using expr: 5 + 3 = 8 10 - 4 = 6 6 \* 7 = 42 20 / 4 = 5 |
|
|
|
|
|
Output:
Length of 'hello': 5 |
|
|
Floating-point arithmetic requires external tools: |
|
|
Output:
Floating-point with bc: 5.5 + 3.2 = 8.7 10 / 3 = 3.33 sqrt(2) = 1.4142 |
|
|
Bash
Bash’s |
|
|
Output:
let result: 8 let x: 6 let y: 12 |
|
|
Bash
Bash’s |
|
|
Output:
x is greater than 5 |
|
|
Bash
Declare integer variables with |
|
|
Output:
Declared int: 8 |
|