10
$ a='"apple","ball","cat"'
$ a='['$a
$ echo $a
["apple","ball","cat"
$ a=$a']'
$ echo $a
b

I'm stumped hard by the result b while I expect to see ["apple,"ball","cat"]. What am I missing here?

This is from bash shell on Mac. Also see it on CentOS 7, while not on Fedora. Can someone please explain?

John Kugelman
  • 2,057
  • 2
  • 16
  • 23

2 Answers2

27

There is a file with the name b in the current directory.

[...]

is a pattern matching expression. It matches every file of which the name consists of a single letter between [ and ].

This is similar to having * in a variable value and using the variable without quotes.

Hauke Laging
  • 90,279
3

Hauke already answered why it's happening. For future reference, you can also troubleshoot what is happening with strace:

$ touch a b l
$ a='["apple","ball"]'                                                      
$ strace -e trace=execve echo $a
execve("/bin/echo", ["echo", "a", "b", "l"], [/* 82 vars */]) = 0
a b l
+++ exited with 0 +++

Or with set -x:

$ set -x; echo $a
+ set -x
+ echo a b l
a b l

It's might not immediately be clear, but at least you see that shell has converted the unquoted variable into a list of items; from there we can deduce that filename expansion occurred.