9

Here goes the riddle:

If I do:

touch file{1,2,3}

It creates file1, file2, file3

And if I do

rm file[1-3]

It deletes them.

but if I do

touch file[1-3] 

it creates:

file[1-3]

Why?

13

If you took the trouble of reading the manpage instead of making riddles:

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] expands into files named file1, file2, file3. Filename expansion happens only if matching files exist. If not, the pattern is left as-is. Therefore, with files named file1, file2, file3, file[1-3] expands to file1 file2 file3. Without these files, it doesn't expand, and remains as file[1-3]. With {...}, the filenames don't have to exist, so file{1..3} expands to file1 file2 file3 irrespective of the files being present or absent.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.