Advanced Features of the [[ Operator

Learn features of the [[ operator besides string comparison.

Logical operations in the [[ operator

We can use logical operations AND, OR, and NOT in the [[ operator. They combine several boolean expressions into a single condition. The following table explains how they work.

Operation Description Example
&& Logical AND [[ -n "$var" && "$var" < "abc" ]] && echo "The string is not empty and it is smaller than \"abc\""
|| Logical OR [[ "abc" < "$var" \|\| -z "$var" ]] && echo "The string is larger than \"abc\" or it is empty"
! Logical NOT [[ ! "abc" < "$var" ]] && echo "The string is not larger than \"abc\""

We can group boolean expressions using parentheses in the [[ operator. Here is an example:

[[ (-n "$var" && "$var" < "abc") || -z "$var" ]] && echo "The string is not empty and less than \"abc\" or the string is empty"

Run the command in the terminal below.

Get hands-on with 1200+ tech skills courses.