Reputation: 10882
I want to decide whether to always omit quotes for variables appearing withing a Bash [[
test. I interpret the man
page to say that it is permissible to do so without any loss of correctness.
I devised this simplistic "test" to verify my thinking and the "expected behaviour" but it may prove absolutely nothing, take a look at it:
x='1 == 2 &&'
if [[ $x == '1 == 2 &&' ]]; then
echo yes
else
echo no
fi
Note I am not writing 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 is safe to switch my coding convention to always omit quotes for variables appearing within [[
tests?
I am trying to learn Bash and I am trying to do so picking up good habits, good style and correctness..
Upvotes: 5
Views: 1969
Reputation: 6577
The key thing to remember is that quotes and escaping within pattern matching contexts always cause their contents to become literal. Quoting on the left hand side of an ==
within [[
is never necessary, only the right side is interpreted as a pattern. Quoting on the right hand side is necessary if you want a literal match and to avoid interpretation of pattern metacharacters within the variable.
In other words, [ "$x" = "$x" ]
and [[ $x == "$x" ]]
are mostly equivalent, and of course in Bash the latter should be preferred.
One quick tip: think of the operators of the [[ ]]
compound comand as being the same grammar-wise as other control operators such as elif
, do
, ;;
, and ;;&
(though technically in the manual they're in their own category). They're really delimiters of sections of a compound command, which is how they achieve seemingly magical properties like the ability to short-circuit expansions. This should help to clarify a lot of the behavior of [[
, and why it's distinct from e.g. the arithmetic operators, which are not like that.
More examples: http://mywiki.wooledge.org/BashFAQ/031#Theory
Upvotes: 9
Reputation: 11933
No. You should not get in the habit of always omitting quotes, even if they appear within [[
tests. Bash is famous for burning people for leaving off quotes :-)
In bash the [[ ]]
should always evaluate as an expression, so the script will continue to function. The risk is that a logic error may pop up unnoticed. In all cases that I can think of off the top of my head it would be fine. However, quotes allow you to be specific about what you want, and are also self-documenting in addition to being safer.
Consider this expression:
if [[ "$INT" =~ ^-?[0-9]+$ ]]; then
It would still work without the quotes because it is in between [[ ]]
, but the quotes are clarifying and do not cause any issues.
At any rate, this is my opinion as a guy who has received a royal hosing at the hand of Bash because I failed to put " "
around something that needed them :'(
My bash hacking friend once said, "use quotes liberally in Bash." That advice has served me well.
Upvotes: 6