fronthem
fronthem

Reputation: 4139

Do we still need to use `[...]` in Bash?

If I don't care about compatibility or portable issues, would I still need to use test construction [...] in Bash?

Many tutorials/books tell that [[...]] is better and more flexible than [...] e.g. [[...]] is support glob/regex, but today I still see many people prefer to use [...] as standard form.

What is a reason behind this? What [...] can do but [[...]] can not do?

Upvotes: 0

Views: 160

Answers (2)

Etan Reisner
Etan Reisner

Reputation: 80921

Other than the portability benefits of [ and the newer features and safety/correctness properties of [[ that have already been discussed there is one downside to using [[ that is worth being aware of (to my mind).

Specifically, what happens when you use it to validate/etc. numeric values.

I asked a question here about it.

I also discussed it in the comments on this answer.

Specifically, this

foo=bar
[ 5 -eq "$foo" ]

will output an error and [ will return 2 whereas this (with or without quotes around the variable)

foo=bar
[[ 5 -eq "$foo" ]]

will silently return 1 and this

bar=5
foo=bar
[[ 5 -eq "$foo" ]]

will return 0.

That is [[ evaluates bare-variables recursively. It also, as indicated in ruakh's comment on chepner's answer will expand expressions in variables.

So

foo="10 / 2"
[[ 5 -eq "$foo" ]]

will also return true.

Now, this may be exactly what you want but means you have to work harder to validate input/etc. then you would with [.

Upvotes: 1

chepner
chepner

Reputation: 530922

I found one bit of functionality that [ implements but [[ does not. However, it's not something you should be using anyway, so I wouldn't call it a reason to use [ over [[.

The -a and -o operators for boolean AND and OR are supported by test:

if [ 3 -eq 3 -a 4 -eq 4 ]; then
    echo true
fi

However, trying to use them with [[ is a syntax error:

# The correct version is
# if [[ 3 -eq 3 && 4 -eq 4 ]]; then echo yay; fi
$ if [[ 3 -eq 3 -a 4 -eq 4 ]]; then echo yay; fi
bash: syntax error in conditional expression
bash: syntax error near `-a'

But if you are using [[, you would use && and || instead, even if -a and -o were supported. Further, even the POSIX standard recommends using [ ... ] && [ ... ] in place of -a (and [ ... ] || [ ... ] instead of -o); the two operators are extensions that aren't required of a conforming POSIX implementation.


Other reasons, aside from portability concerns, are simply going to be matters of opinion.

Upvotes: 1

Related Questions