Bash 中的括号、花括号和花括号

Bash 中的括号、花括号和花括号

谜底如下:

如果我做:

touch file{1,2,3}

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

如果我这么做

rm file[1-3]

它会删除它们。

但如果我这么做

touch file[1-3] 

它创建:

file[1-3]

为什么?

答案1

如果你花时间阅读手册页而不是制造谜语:

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.

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

相关内容