bash extglob range-or-value matching same file name twice

307 views Asked by At

Given these files:

$ ls
file1  file2  file21  file3  fileFoo

I expected this globbing pattern (bash with extglob enabled):

$ ls file?({1..2}|Foo)

to output:

file1  file2  fileFoo

but instead I got this with fileFoo listed twice:

$ ls file?({1..2}|Foo)
file1  file2  fileFoo  fileFoo

Neither side of the "or" produces unexpected results:

$ ls file?({1..2})
file1  file2

$ ls file?(Foo)
fileFoo

so why is fileFoo printed twice when I "or" the expressions and what would be the correct globbing pattern to match a range (e.g. 1-2 above but could be 17-593 or any other range) or some other unrelated string (e.g. Foo above)?

$ bash --version
GNU bash, version 4.4.12(3)-release (x86_64-unknown-cygwin)
2

There are 2 answers

0
Ignacio Vazquez-Abrams On BEST ANSWER

Expansion is performed before globbing:

file?({1..2}|Foo) 

becomes

file?(1|Foo) file?(2|Foo)

and then both arguments are globbed.

Using only expansion as follows works as expected, but will trip up nullglob and the like:

file{{1..2},Foo}
1
Barmar On

It's being interpreted as:

ls file?(1|Foo) file?(2|Foo)

The range is being expanded and then each value is combined with |Foo.

So when each pattern is expanded, you get both the file ending with a number and the file ending with Foo.

Try:

ls file{{1..2},Foo)