|
|
|
Shell scripting supports arithmetic operations through several mechanisms. This example covers the main ways to do math in shell scripts. |
|
|
POSIX arithmetic expansion with $(( )): |
|
|
Variables in arithmetic (no $ needed inside): |
|
|
Compound assignment: |
|
|
Bash
Bash provides shorter increment/decrement: |
|
|
Comparison operators (return 1 for true, 0 for false): |
|
|
Logical operators: |
|
|
Bitwise operators: |
|
|
Ternary operator: |
|
|
Parentheses for grouping: |
|
|
Different bases: |
|
|
Using expr (older method, POSIX): |
|
|
expr for string length and matching: |
|
|
Floating-point arithmetic requires external tools: |
|
|
Using awk for floating-point: |
|
|
Bash
Bash’s let command: |
|
|
Bash’s (( )) for arithmetic in conditions: |
|
|
Declare integer variables: |
|
|
Random number generation: |
|
|
Practical examples: |
|
|
Calculate percentage: |
|
|
Loop counter: |
|
|
Temperature conversion: |
|
|
Powers (bash only has ** operator, use bc for POSIX): |
|