Using the [[ keyword

Bash provides its own improved version of the [ command, doubling it to [[. It's actually a shell keyword, a special part of the Bash syntax, and not just a regular builtin command:

#!/bin/bash
myshell=bash
if [[ $myshell = 'bash' ]] ; then
    printf 'Match!\n'
fi

One advantage of the [[ keyword over the [ builtin is that less quoting is required. You may notice in the preceding example that $myshell is not in double quotes.

Unfortunately, this benefit does not apply to the right-hand side of the =, ==, !=, or =~ operations. If you're testing two variables for equality, for example, you will still need to quote the one to the right of the equals sign:

[[ $myshell = "$yourshell" ]]

If you find this too confusing (or imbalanced!), ...

Get Bash Quick Start Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.