Bash中的括号,括号,花括号


9

谜语在这里:

如果我做:

touch file{1,2,3}

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

如果我愿意

rm file[1-3]

删除它们。

但是如果我这样做

touch file[1-3] 

它创建:

file[1-3]

为什么?


1
尝试重复shopt -s nullglob之前做的事情-您会明白的。参见mywiki.wooledge.org/glob
Rmano

Answers:


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.

file[1-3]扩展到指定的文件file1file2file3。仅当存在匹配文件时,才进行文件名扩展。如果不是,则模式保持原样。因此,命名文件file1file2file3file[1-3]扩展到file1 file2 file3。没有这些文件,它不会扩展,并保持为file[1-3]。使用{...},文件名不必存在,因此file{1..3}扩展为,file1 file2 file3无论文件存在与否。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.