Bash 5 reference · Shell Builtins and Syntax
[[ ]] (Bash syntax)
Bash's conditional expression: compare strings and numbers, test files, and match glob patterns or regular expressions.
Bash 5
Syntax
[[ EXPRESSION ]]
Parameters
| Parameter | Description |
|---|---|
-f / -d / -e |
Regular file / directory / exists. |
-z / -n |
String is empty / not empty. |
== / != |
String (glob) comparison. |
=~ |
Regular expression match; captures go to BASH_REMATCH. |
-eq -lt -gt |
Integer comparison (or use (( ))). |
&& || ! |
Combine conditions. |
Examples
touch app.log
[[ -f app.log && ! -d app.log ]] && echo 'app.log is a file'
name=report.csv
[[ $name == *.csv ]] && echo 'CSV by glob'
Output
app.log is a file CSV by glob
Run this on your computer — see “Get Started” for setup.
version=v2.14.3
if [[ $version =~ ^v([0-9]+)\.([0-9]+) ]]; then
echo "major=${BASH_REMATCH[1]} minor=${BASH_REMATCH[2]}"
fi
Output
major=2 minor=14
Run this on your computer — see “Get Started” for setup.
Inside [[ ]] variables don't need quotes to avoid word splitting, but quote the right side of == to compare literally instead of as a pattern.
Related
if· Run commands depending on whether a command succeeds (exit status 0), with optional elif and else branches.case· Match a value against glob patterns and run the first matching branch; cleaner than long if/elif chains.- Bash Conditionals: if, [[ ]] and case · tutorial