返回 2026-06-29
🛠 工具 / 开源

大括号扩展树Brace expansion tree

johndcook.com·2026-06-28 节选正文

一个巧妙的 Bash 单行命令 `echo {w,t,}h{e{n{,ce{,forth}},re{,in,fore,with{,al}}},ither,at}` 能够一次性生成 30 个合法的英语单词。该命令利用了 Bash Shell 的大括号扩展机制,通过类似树状图的嵌套结构来组合词根和词缀。通过剖析这个特殊的语法树,可以深入理解 Shell 脚本中字符串生成的底层逻辑和递归组合原理。这种极客般的技巧展示了命令行工具在处理复杂文本模式时的强大能力。

John

Here’s a crazy bash one-liner I found via an article by Peter Krumins:

echo {w,t,}h{e{n{,ce{,forth}},re{,in,fore,with{,al}}},ither,at}

This prints 30 English words:

when, whence, whenceforth, where, wherein, wherefore, wherewith, wherewithal, whither, what, then, thence, thenceforth, there, therein, therefore, therewith, therewithal, thither, that, hen, hence, henceforth, here, herein, herefore, herewith, herewithal, hither, hat

This post will explain how the one-liner works.

Bash brace expansion iterates through all possibilities listed within curly braces, with possibilities separated by a comma. Note that the comma is a separator and not a terminator. And so, for example, the expression {w,t,} is effectively {w,t,""}.

When bash sees two brace expressions, these expand to the cartesian product of the two expressions. For example,

echo {A,B}{1,2,3}

produces

A1 A2 A3 B1 B2 B3

In the expression above we have

{w,t,}h{e…,ither,at}

So the expansion will enumerate all possibilities of {w,h,} multiplied by all possibilities of {e…,ither,at} where e… is itself a brace expression.

A diagram will help a lot.

The brace expansion does a depth-first traversal of this tree.

需要完整排版与评论请前往来源站点阅读。