Bash 中的括号、大括号、花括号

Ulu*_*kai 9 bash syntax

谜底来了:

如果我做:

touch file{1,2,3}
Run Code Online (Sandbox Code Playgroud)

它创建文件 1、文件 2、文件 3

如果我这样做

rm file[1-3]
Run Code Online (Sandbox Code Playgroud)

它会删除它们。

但如果我这样做

touch file[1-3] 
Run Code Online (Sandbox Code Playgroud)

它创建:

file[1-3]
Run Code Online (Sandbox Code Playgroud)

为什么?

mur*_*uru 13

如果您不厌其烦地阅读手册而不是制作谜语:

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. 
...
Pathname Expansion
   After  word  splitting,  unless  the -f option has been set, bash scans
   each word for the characters *, ?, and [.  If one of  these  characters
   appears,  then  the word is regarded as a pattern, and replaced with an
   alphabetically sorted list  of  filenames  matching  the  pattern  (see
   Pattern  Matching  below). If no matching filenames are found, and the
   shell option nullglob is not enabled, the word is left  unchanged.
...
Pattern Matching

   Any character that appears in a pattern, other than the special pattern
   characters described below, matches itself.  ...

   The special pattern characters have the following meanings:

   ...
          [...]  Matches  any  one  of the enclosed characters.  A pair of
                 characters  separated  by  a  hyphen  denotes   a   range
                 expression;  any  character  that falls between those two
                 characters,  inclusive,  using   the   current   locale's
                 collating sequence and character set, is matched.
Run Code Online (Sandbox Code Playgroud)

file[1-3]扩展为名为file1, file2, 的文件file3。仅当存在匹配的文件时才会发生文件名扩展。如果不是,则模式保持原样。因此,对于名为file1, file2, 的文件file3file[1-3]扩展为file1 file2 file3. 没有这些文件,它不会扩展,并保持为file[1-3]. 使用{...},文件名不必存在,因此无论文件存在或不存在都会file{1..3}扩展到file1 file2 file3