谁能解释一下这个 shell bash 命令 "echo{,}" 是什么意思?

Could someone explain me what this shell bash command "echo{,}" means?

如果我这样做:

echo{,}

结果是:

echo

最后的{,}和结果我不是很懂 感谢澄清这一点。

echo{,}

只打印 echo 因为它等同于 echo echo.

更多示例需要说明:

bash -xc 'echo{,}'
+ echo echo
echo

echo foo{,}
foo foo

echo foo{,,}
foo foo foo

More about Brace Expansion

Brace expansion is a mechanism by which arbitrary strings may be generated. This mechanism is similar to pathname expansion, but the filenames generated need not exist. Patterns to be brace expanded take the form of an optional preamble, followed by either a series of comma-separated strings or a sequence expression between a pair of braces, followed by an optional postscript. The preamble is prefixed to each string contained within the braces, and the postscript is then appended to each resulting string, expanding left to right.

{item1,item2,...} 是大括号展开。

所以 echo{,} 扩展为 echo echo 因为 {,} 有两个(空)元素,然后 echo 打印它的参数。

试试这个:

$ set -x
$ echo{,}
+ echo echo
echo
$ set +x
+ set +x
$

我将从一些更简单的东西开始,看看 {} 是如何工作的:作为 @anubhava 的链接,它会生成字符串。本质上,它扩展了其中的所有元素,并将它们与它前后的任何元素组合在一起(如果不引用,space 是分隔符)。

示例:

$ bash -xc 'echo before{1,2}after and_sth_else'
+ echo before1after before2after and_sth_else
before1after before2after and_sth_else

注意 echo 和参数之间有一个 space。您发布的内容并非如此。那么那里发生了什么?检查以下内容:

$ bash -xc 'man{1,2}'
+ man1 man2
bash: man1: command not found

扩展的结果被提供给bash并且bash尝试执行它。在上面的例子中,要查找的命令是 man1(不存在)。

最后,结合以上问题:

  • echo{,}
    • {,}扩展为两个空elements/strings
    • 然后这些 prefixed/concatenated 带有“回声”,所以我们现在有 echo echo
    • 扩展完成,交给bash执行
    • 命令是 echo 并且它的第一个参数是“echo”...所以它回显 echo!

在没有嵌套循环的情况下生成“叉积”也很方便:

$ ary=( {1,2,3}{a,b,c} )
$ declare -p ary
declare -a ary=([0]="1a" [1]="1b" [2]="1c" [3]="2a" [4]="2b" [5]="2c" [6]="3a" [7]="3b" [8]="3c")