Kurung, Kawat Gigi, Kurung Keriting di Bash

9

Ini dia teka-teki:

Jika aku melakukan:

touch file{1,2,3}

Itu menciptakan file1, file2, file3

Dan jika saya lakukan

rm file[1-3]

Itu menghapus mereka.

tetapi jika saya lakukan

touch file[1-3] 

itu menciptakan:

file[1-3]

Mengapa?

Ulukai
sumber
1
Cobalah untuk mengulanginya shopt -s nullglobsebelum - Anda akan memahaminya. Lihat mywiki.wooledge.org/glob
Rmano

Jawaban:

13

Jika Anda kesulitan membaca manual daripada membuat teka-teki:

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]mengembang ke file bernama file1, file2, file3. Ekspansi nama file hanya terjadi jika ada file yang cocok. Jika tidak, polanya dibiarkan apa adanya. Oleh karena itu, dengan file bernama file1, file2, file3, file[1-3]memperluas ke file1 file2 file3. Tanpa file-file ini, itu tidak berkembang, dan tetap seperti file[1-3]. Dengan {...}, nama file tidak harus ada, jadi file{1..3}perluas file1 file2 file3terlepas dari file yang ada atau tidak ada.

muru
sumber