2

After setting:

var1="a\nb"
var2="$var1"

I expect $var1 and $var2 to be equal; however:

[[ $var1 == $var2 ]] && echo yes || echo no

returns no. Why is that?

fedorqui
  • 275,237
  • 103
  • 548
  • 598

1 Answers1

8

You have to quote to perform the string comparison:

[[ "$var1" == "$var2" ]]

So this works:

$ var1="a\nb"
$ var2="$var1"
$ [[ "$var1" == "$var2" ]] && echo yes || echo no
yes

Why is this happening?

From the comments, chepner indicates:

Without the quotes, $var2 is interpreted as a pattern, not a string, and the \n is treated as a regular n.

Community
  • 1
  • 1
fedorqui
  • 275,237
  • 103
  • 548
  • 598
  • `echo "$var1"` displays `a\nb`. Why it fails to display a newline? – Avinash Raj Nov 06 '14 at 15:08
  • `bash` doesn't interpret backslash escapes by default. You need to use `echo -n "$var1"` instead. – chepner Nov 06 '14 at 15:10
  • @AvinashRaj `\n` does not suffice. You need something like `var1="a"$'\n'"b"`. See [Trying to embed newline in a variable in bash](http://stackoverflow.com/a/9139891/1983854) for more info. – fedorqui Nov 06 '14 at 15:11
  • 2
    Without the quotes, `$var2` is interpreted as a pattern, not a string, and the `\n` is treated as a regular `n`, so `[[ anb == $var2 ]]` would succeed. – chepner Nov 06 '14 at 15:12
  • @chepner thanks a lot (as always) for the deeper explanation. I added your comment into the answer. – fedorqui Nov 06 '14 at 15:15
  • 2
    Only the rhs of `==` needs to be quoted: `[[ $var1 == "$var2" ]]` is enough. From the manual: _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 in Pattern Matching._ – gniourf_gniourf Nov 06 '14 at 15:20
  • 1
    ah - after reading [link](http://stackoverflow.com/questions/3427872/whats-the-difference-between-and-in-bash) I thought that would not be needed. Thanks. – Wybo Dekker Nov 06 '14 at 15:24