Why does `cat` seem to iterate over JSON arrays?

I’m puzzled by this behaviour of cat when trying to output a heredoc containing JSON in bash 3.2:

input:

$ cat <(cat <<EOF
> {"x":[{"a":1,"b":2}]}
> EOF)

output:

{"x":["a":1]}
{"x":["b":2]}

What’s going on?

Asked By: Armand

||

This is just shell variable expansion by bash. In this context whatever is between the curly braces will be iterated and expanded into the expression.

$ echo var{1,2,3,4}
var1 var2 var3 var4

$ echo var{1..10}
var1 var2 var3 var4 var5 var6 var7 var8 var9 var10
Answered By: casey

Not an answer, but a formatted comment:

$ cat <(cat <<EOF
> {"x":[{"a":1,"b":2}]}
> EOF)
bash: warning: here-document at line 15 delimited by end-of-file (wanted `EOF')
bash: warning: here-document at line 15 delimited by end-of-file (wanted `EOF')
{"x":[{"a":1,"b":2}]}

Put the closing parenthesis on a new line

$ cat <(cat <<EOF
> {"x":[{"a":1,"b":2}]}
> EOF
> )
{"x":[{"a":1,"b":2}]}

and clearly, I can’t reproduce:

$ echo $BASH_VERSION
4.3.39(1)-release
Answered By: glenn jackman

Brace expansion is subject to the “braceexpand” option. For example:

set +B
cat <(cat <<EOF
{"x":[{"a":1,"b":2}]}
EOF
)

produces the single JSON value.

Answered By: peak
Categories: Answers Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.