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?

8
  • Some of your lines begin with a dollar sign ($). Is that the Bash prompt or are you typing that in? Commented Nov 14, 2017 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. Commented Nov 14, 2017 at 22:24
  • What do you get if you run it under set -xv? Commented Nov 14, 2017 at 22:28
  • Sorry, yes, that is indeed the bash prompt. Commented Nov 14, 2017 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 Commented Nov 14, 2017 at 22:37

2 Answers 2

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.

2
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.