Bash – Recursive Glob

bashrecursiveshellwildcards

I'd like to write something like this:

$ ls **.py

in order to get all .py filenames, recursively walking a directory hierarchy.

Even if there are .py files to find, the shell (bash) gives this output:

ls: cannot access **.py: No such file or directory

Any way to do what I want?

EDIT: I'd like to specify that I'm not interested in the specific case of ls, but the question is about the glob syntax.

Best Answer

In order to do recursive globs in bash, you need the globstar feature from bash version 4 or higher.

From the bash manpage:

globstar
    If set, the pattern ** used in a pathname 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.

For your example pattern:

shopt -s globstar
ls -d -- **/*.py
Related Question