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]擴展為名為file1, file2,的檔案file3。僅當存在匹配文件時才會發生文件名擴展。如果不是,則圖案保持原樣。因此,如果檔案名稱為file1, file2, file3, 則file[1-3]擴展為file1 file2 file3.如果沒有這些文件,它就不會擴展,並保持為file[1-3].使用 時{...},檔案名稱不必存在,因此無論檔案存在或不存在,file{1..3}都會擴展為。file1 file2 file3

相關內容