Conditional tests with brackets and arithmetic
- Version
- 5.3
- Review
- Draft
Summary#
Use [[ ]] for Bash string, pattern, and file tests, [ ] for portable test expressions, and (( )) for arithmetic conditions. if takes the branch when the condition returns status zero.
Syntax#
[[ $file == *.csv ]] # Shell pattern match
[[ $file == "$expected" ]] # Literal string comparison
[[ $file =~ $regex ]] # Extended regular expression
[ -n "$file" ] # Nonempty string
[ "$count" -gt 0 ] # Integer comparison with test
(( count >= 2 )) # Arithmetic expression
Bash skips word splitting and filename expansion on expansions inside [[ ]]. The (( )) command succeeds when the expression evaluates to a nonzero number.
Example#
These tests check a filename against a pattern, confirm that it is present, and compare a record count.
file='daily report.csv'
extension='*.csv'
count=2
if [[ $file == $extension ]]; then
printf '%s\n' 'CSV pattern matched'
fi
if [ -n "$file" ]; then
printf '%s\n' 'filename is present'
fi
if (( count >= 2 )); then
printf '%s\n' 'at least two records'
fi
Expected output#
CSV pattern matched
filename is present
at least two records
Common mistakes#
Quote expansions passed as operands to [ ] and keep the closing ] as its own argument. With [[ ]], quote the right-hand side of == for a literal match and leave it unquoted for a pattern match. Pass only trusted arithmetic expressions to (( )). Bash can evaluate the contents of a variable as an expression, and integer constants with a leading zero are octal.
Version applicability#
The complete example works on Bash 3.2. The =~ operator was added in Bash 3.0. Starting with Bash 3.2, quoting part of the regular expression makes that part match literally under the default compatibility settings.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0