testing
(( )) arithmetic
Bash arithmetic evaluation — treats operands as integers and supports C-style operators (+, -, *, /, %, **, <<, >>, &, |, ^, &&, ||, !, ==, !=, <, >, ternary). (( )) returns exit status 0 if EXPR is non-zero, 1 if zero; $(( )) substitutes the result as a string.
(( EXPR )) | $(( EXPR )) Common flags / operators
| Flag / Operator | Purpose |
|---|---|
| + - * / % | Basic arithmetic (integer division) |
| ** | Exponentiation |
| ++ -- | Pre/post increment and decrement |
| == != < <= > >= | Comparisons (result is 0 or 1) |
| ? : | Ternary conditional |
| $(( )) | Arithmetic substitution — expands to the numeric result |
Examples
(( count++ )) Increment count in place — no $ needed on variables.
if (( a > b )); then echo bigger; fi Numeric comparison with natural operator syntax.
sum=$(( 1 + 2 * 3 )) Assign the result (7) using arithmetic substitution.
(( n = n > 0 ? n : -n )) Ternary — absolute value assignment.
Gotcha
(( )) treats a result of 0 as FALSE (exit 1) — so 'x=0; (( x ))' fails, which can trip 'set -e'. Bash integers only; use bc/awk for floating point.
Related
[[ ]]
Bash-specific conditional expression with safer parsing, glob and regex matching, and short-circuit logical operators. No word splitting or filename expansion happens on the arguments, so quoting is far less error-prone than [ ] — but [[ ]] is not POSIX.
test / [ ]
POSIX conditional expression evaluator — tests file attributes, string comparisons, and integer comparisons, returning exit status 0 (true) or 1 (false). [ is a command (with a required closing ]), not syntax — arguments must be separated by spaces.
declare / typeset / readonly
Declares variables with attributes: arrays, associative arrays, integers, readonly, lowercase/uppercase, exported. 'readonly' is a shortcut for 'declare -r' that locks a variable so it cannot be reassigned or unset for the lifetime of the shell.