Problem Statement
How do you perform arithmetic operations in bash? Explain different methods and their use cases.
Explanation
Bash arithmetic expansion using $(( expression )): performs integer arithmetic. Operators: + (addition), - (subtraction), * (multiplication), / (integer division), % (modulus), ** (exponentiation). Example: RESULT=$((5 + 3)) assigns 8, RESULT=$((10 / 3)) assigns 3 (integer division). Variables don't need $ inside (( )): RESULT=$((VAR1 + VAR2)).
Increment/decrement: ((VAR++)) increments, ((VAR--)) decrements, ((VAR+=5)) adds 5. Assignment operators: +=, -=, *=, /=, %=. Comparison returns 0 (false) or 1 (true): (( 5 > 3 )) returns true. Use in conditionals: if (( VAR > 10 )); then echo "Greater"; fi.
Let command alternative: let "RESULT=5+3" or let RESULT=5+3 (no quotes if no spaces). Multiple operations: let "X=5" "Y=10" "Z=X+Y". Can use without assigning: let "counter++".
Expr command for portability (POSIX): RESULT=$(expr 5 + 3) requires spaces around operators. Multiplication needs escaping: expr 5 \* 3. Less efficient than $(( )) due to external command, but works in all shells.
Floating-point arithmetic: bash only supports integers, use bc or awk for decimals. Example: RESULT=$(echo "scale=2; 10/3" | bc) gives 3.33 with 2 decimal places. Awk: RESULT=$(awk "BEGIN {print 10/3}").
Random numbers: $RANDOM generates random integer 0-32767. Range: RAND=$((RANDOM % 100)) gives 0-99. Seed: RANDOM=seed sets seed for reproducible sequence.
Common patterns: loop counter: for ((i=0; i<10; i++)); do echo $i; done. Calculate percentage: PERCENT=$((VALUE * 100 / TOTAL)). Understanding arithmetic enables numeric processing, counters, calculations, and mathematical operations in scripts.