Bash [[tests quoting variables

I want to decide whether to always omit quotation marks for variables that appear when testing Bash [[ . I interpret the man page to say that it is permissible to do this without any loss of validity.


I designed this simplified “test” to test my thinking and “expected behavior”, but it may turn out to be absolutely nothing, take a look at it:

 x='1 == 2 &&'; if [[ $x == '1 == 2 &&' ]]; then echo yes; else echo no; fi 

Note. I do not write this as such:

 x='1 == 2 &&'; if [[ "$x" == '1 == 2 &&' ]]; then echo yes; else echo no; fi 

which so far has always been my style, for consistency, if nothing else.


Is it safe to switch my coding convention to always skip quotes for variables included in tags [[ ?

I am trying to learn Bash, and I am trying to do this in order to gain good habits, good style and correctness.

+4
source share
2 answers

The main thing to remember is that quotation marks and escaping in pattern matching contexts always cause their contents to become literal. Quoting on the left side == inside [[ never required, only the right side is interpreted as a template. The quote on the right side is necessary if you want to have a literal match and avoid interpreting the template metacharacters within the variable.

In other words, [ "$x" = "$x" ] and [[ $x == "$x" ]] are basically equivalent, and of course, in Bash, the latter should be preferred.

One quick tip: think that the layout [[ ]] statements are the same grammar as other control statements such as elif , do , ;; and ;;& (although technically in the manual they are in their own category). They really are the separators of the sections of a complex team, and this is how they achieve seemingly magical properties, such as the ability to short-circuited extensions. This should help clarify most of the behavior [[ and why it differs from, for example, arithmetic operators that are different.

Other examples: http://mywiki.wooledge.org/BashFAQ/031#Theory

+5
source

No. You should not get used to always miss quotes, even if they appear in the [[ . Bash is known for burning people by leaving quotes :-)

In Bash, the value [[ ]] should always be evaluated as an expression, so the script will continue to function. The risk is that a logical error may appear unnoticed. In all cases, when I can think of my head, everything will be fine. However, quotes allow you to be specific about what you want, as well as self-documenting in addition to being more secure.

Consider this expression:

if [[ "$INT" =~ ^-?[0-9]+$ ]]; then

It will work without quotes because it is between [[ ]] , but the quotes specify and do not cause any problems.

Anyway, this is my opinion as the guy who got the royal hoses for Bash’s hand because I couldn’t put a " " around something they needed: '(

My younger friend Bash once said, "Use quotes liberally in Bash." This advice has served me well.

+3
source

All Articles