2

Looking at other Bash scripts, I see people comparing variables like: $S == $T while at other times I see the variable being wrapped inside strings: "$S" == "$T".

Some experiments seem to suggest that both do the same. The demo below will print equal in both cases (tested with GNU bash, version 4.2.37):

#!/usr/bin/env bash

S="text"
T="text"

if [[ $S == $T ]]; then
  echo "equal"
fi

if [[ "$S" == "$T" ]]; then
  echo "equal"
fi

My question: if there's a difference between $S == $T and "$S" == "$T", what is it?

1 Answer 1

5

If you use [[ they are almost the same, but not quite...

When the == and != operators are used, the string to the right of the operator is considered a pattern and matched according to the rules described below under Pattern Matching. [...] Any part of the pattern may be quoted to force it to be matched as a string.

If you use [ then you have to use quotes unless you know that the variables cannot be empty or contain whitespace.

Just to be on the safe side, you probably want to quote all your variables all the time.

Sign up to request clarification or add additional context in comments.

2 Comments

Ah, cool, it's the [...] and [[...]] that makes the difference. Now I have a starting point to look in the manual for more info. Thanks Karoly!
Actually, you should double-quote at least the right operand in [[...]], otherwise it'll get treated as a pattern rather than just a string (e.g. if T='*', [[ $S == $T ]] will always be true). I recommend just double-quoting all variables rather than trying to keep track of where it's safe vs. unsafe.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.