Staffe, parentesi graffe, parentesi graffe in Bash


9

Ecco l'enigma:

Se lo faccio:

touch file{1,2,3}

Crea file1, file2, file3

E se lo faccio

rm file[1-3]

Li cancella.

ma se lo faccio

touch file[1-3] 

crea:

file[1-3]

Perché?


1
Prova a ripeterlo facendo shopt -s nullglobprima: lo capirai. Vedi mywiki.wooledge.org/glob
Rmano,

Risposte:


13

Se ti sei preso la briga di leggere la manpage invece di fare enigmi:

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]si espande in file denominati file1, file2, file3. L'espansione del nome file avviene solo se esistono file corrispondenti. In caso contrario, il modello viene lasciato così com'è. Pertanto, con file denominati file1, file2, file3, file[1-3]espande file1 file2 file3. Senza questi file, non si espande e rimane come file[1-3]. Con {...}, i nomi dei file non devono esistere, quindi si file{1..3}espandono file1 file2 file3indipendentemente dal fatto che i file siano presenti o assenti.

Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.