What do double-asterisk wildcards mean?

Mike Blair picture Mike Blair · Jan 27, 2015 · Viewed 50.8k times · Source

I've tried the following command but I am having trouble interpreting it:

ls **

but I'm not sure exactly what it is outputting and why that is the result.

Answer

Keith Thompson picture Keith Thompson · Jan 28, 2015

It's probably using a special feature of some shells that lets ** do a recursive match, as opposed to a single *, which matches only in the current directory.

The wildcard * matches any file or directory (whose name doesn't start with .) in the current directory.

Depending on which shell you're using, and with which settings, ** may be equivalent to *; it could match zero or more characters followed by zero or more characters, which is the same as matching zero or more characters just once.

But with some shells, with some settings, ** is a recursive version of *, matching all files and directories in the current directory and subdirectories.

Quoting the bash manual:

`*'
Matches any string, including the null string. When the `globstar' shell option is enabled, and `*' is used in a filename expansion context, two adjacent `*'s used as a single pattern will match all files and zero or more directories and subdirectories. If followed by a `/', two adjacent ``*'s will match only directories and subdirectories.

This works only if the globstar option is set via:

shopt -s globstar

(it's disabled by default) and only in relatively recent versions of bash.

I believe zsh also supports this syntax.

It's important to keep in mind that wildcards are expanded by the shell, not by the ls command. If you type ls **, or ls *.txt, the ls command itself never sees the * characters; it only sees an expanded list of files, just as if you had typed the entire list on the command line.