Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is double square brackets [[ ]] preferable over single square brackets [ ] in Bash?

A coworker claimed recently in a code review that the [[ ]] construct is to be preferred over [ ] in constructs like

if [ "`id -nu`" = "$someuser" ] ; then      echo "I love you madly, $someuser" fi 

He couldn't provide a rationale. Is there one?

like image 896
Leonard Avatar asked Mar 21 '09 15:03

Leonard


People also ask

What do double square brackets mean in bash?

Double Brackets i.e. [[]] is an enhanced (or extension) version of standard POSIX version, this is supported by bash and other shells(zsh,ksh). In bash, for numeric comparison we use eq , ne , lt and gt , with double brackets for comparison we can use == , != , <, and > literally. [ is a synonym for test command.

Why do we use double brackets in shell script?

The double bracket is a “compound command” where as test and the single bracket are shell built-ins (and in actuality are the same command). Thus, the single bracket and double bracket execute different code. The test and single bracket are the most portable as they exist as separate and external commands.

What is the difference between and [[ in bash?

"The most important difference will be the clarity of your code.": No, the difference is that [ is a command, while [[ is a syntax element ("reserved word"). Thus the different parsing.

What are square brackets used for in bash?

The square brackets are a synonym for the test command. An if statement checks the exit status of a command in order to decide which branch to take. grep -q "$text" is a command, but "$name" = 'Bob' is not--it's just an expression.


1 Answers

[[ has fewer surprises and is generally safer to use. But it is not portable - POSIX doesn't specify what it does and only some shells support it (beside bash, I heard ksh supports it too). For example, you can do

[[ -e $b ]] 

to test whether a file exists. But with [, you have to quote $b, because it splits the argument and expands things like "a*" (where [[ takes it literally). That has also to do with how [ can be an external program and receives its argument just normally like every other program (although it can also be a builtin, but then it still has not this special handling).

[[ also has some other nice features, like regular expression matching with =~ along with operators like they are known in C-like languages. Here is a good page about it: What is the difference between test, [ and [[ ? and Bash Tests

like image 80
Johannes Schaub - litb Avatar answered Sep 20 '22 01:09

Johannes Schaub - litb