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.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
In order to do recursive globs in bash, you need the globstar feature from Bash version 4 or higher.
From the Bash documentation:
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.
For your example pattern:
shopt -s globstar ls -d -- **/*.py
Method 2
find . -name '*.py'
** doesn’t do anything more than a single *, both operate in the current directory
Method 3
Since Bash 4 (also including zsh) a new globbing option (globstar) has been added which treats the pattern ** differently when it’s set.
It is matching the wildcard pattern and returning the file and directory names that match then by replacing the wildcard pattern in the command with the matched items.
Normally when you use **, it works similar to *, but it’s recurses all the directories recursively (like a loop).
To see if it’s enabled, check it by shopt globstar (in scripting, use shopt -q globstar).
The example **.py would work only for the current directory, as it doesn’t return list of directories which can be recurses, so that’s why you need to use multiple directory-level wildcard **/*.py, so it can go deeper.
Look here for examples of finding files recursively.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0