Bash Operators
Bash supports arithmetic expansion for math and dedicated test operators for comparing numbers and strings.
Arithmetic Expansion with $(( ))
Bash performs integer math inside $(( )), called arithmetic expansion. Variables inside it do not need a leading $, though using one is allowed. The result of the expression can be printed directly, stored in another variable, or used anywhere a value is expected. Bash arithmetic only handles integers -- there is no built-in floating point support.
Example
#!/bin/bash
a=10
b=3
echo "Sum: $((a + b))"
echo "Remainder: $((a % b))"
echo "Power: $((a ** 2))"
((a++))
echo "a after increment: $a"Common Arithmetic Operators
- + and - -- addition and subtraction
- * and / -- multiplication and integer division
- % -- remainder (modulo)
- ** -- exponentiation
- ++ and -- -- increment and decrement
Comparison Operators: Numeric vs String
Numeric and string values use different comparison operators inside [ ] or [[ ]]. Numeric tests use two-letter mnemonics like -eq and -lt, while string tests reuse familiar symbols like = and !=. Mixing them up -- for example using == to compare numbers -- can silently produce wrong results because it performs a string comparison instead of a numeric one.
Example
#!/bin/bash
score=85
passing=60
if [ "$score" -ge "$passing" ]; then
echo "You passed with $score points"
else
echo "You did not pass"
fiString comparisons should be done inside [[ ]] when possible, since it avoids word-splitting surprises and supports pattern matching with ==. Inside plain [ ], always quote the variables being compared so an empty value does not break the test into invalid syntax.
Example
#!/bin/bash
role="admin"
if [[ "$role" == "admin" ]]; then
echo "Full access granted"
elif [[ -z "$role" ]]; then
echo "No role set"
else
echo "Limited access"
fiExercise: Bash Operators
Inside a `[ ]` test, which operator correctly compares two integers for equality?