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?

  • Some of your lines begin with a dollar sign ($). Is that the Bash prompt or are you typing that in? – cherdt Nov 14 '17 at 22:23
  • I'm assuming the dollar signs are Bash prompts, in which case I am not able to reproduce the behavior you've described. – cherdt Nov 14 '17 at 22:24
  • What do you get if you run it under set -xv? – choroba Nov 14 '17 at 22:28
  • Sorry, yes, that is indeed the bash prompt. – Coder321 Nov 14 '17 at 22:36
  • @choroba, this is what I see a=[$a] a=[$a] + a='["apple","ball","cat"]' but when I do echo $a + echo b b – Coder321 Nov 14 '17 at 22:37
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.

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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.