Bash

為什麼 cat 似乎會遍歷 JSON 數組?

  • September 8, 2015

我對cat嘗試在 bash 3.2 中輸出包含 JSON 的heredoc 時的這種行為感到困惑:

輸入:

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

輸出:

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

這是怎麼回事?

這只是 bash 的 shell 變數擴展。在這種情況下,花括號之間的任何內容都將被迭代並擴展為表達式。

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

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

不是答案,而是格式化的評論:

$ 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}]}

將右括號換行

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

很明顯,我無法重現:

$ echo $BASH_VERSION
4.3.39(1)-release

引用自:https://unix.stackexchange.com/questions/213592