Search code examples
bashfiledirectoryglob

Matching partial filenames with the "**" pattern


The documentation on the globstar bash option reads:

globstar

If set, the pattern ‘**’ used in a filename expansion context will match all files and zero or more directories and subdirectories. If the pattern is followed by a ‘/’, only directories and subdirectories match.

That made me think that given a hierarchy like this:

└── dir1
    └── dir2
        └── dir3
            └── file.txt

I could match file.txt in this tree structure using a pattern like **file*. But it doesn't work:

ls **file*
ls: cannot access '**file*': No such file or directory

This works though:

ls **/file*
dir1/dir2/dir3/file.txt

I wonder if ** is supposed to match either a file's directory or a full filename. Links to more precise documentation would be appreciated.


Solution

  • The documentation for node-glob, which handles the expansion of ** the same way as Bash, seems more precise:

    If a "globstar" (**) is alone in a path portion, then it matches zero or more directories and subdirectories searching for matches. It does not crawl symlinked directories.

    [.. The double-star character] is supported in the manner of bsdglob and bash 4.3, where ** only has special significance if it is the only thing in a path part. That is, a/**/b will match a/x/y/b, but a/**b will not.

    So ** must be the only thing in a path part.