Table of Contents

Pathname expansion (globbing)

General

Unlike on other platforms you may have seen, on UNIX®, the shell is responsible for interpreting and expanding globs ("filename wildcards"). A called program will never see the glob itself; it will only see the expanded filenames as its arguments (here, all filenames matching *.log):

grep "changes:" *.log

The base syntax for the pathname expansion is the pattern matching syntax. The pattern you describe is matched against all existing filenames and the matching ones are substituted. Since this substitution happens after word splitting, all resulting filenames are literal and treated as separate words, no matter how many spaces or other IFS-characters they contain.

Normal behaviour

Customization

nullglob

Normally, when no glob specified matches an existing filename, no pathname expansion is performed, and the globs are not removed:

$ echo "Textfiles here:" *.txt
Textfiles here: *.txt
In this example, no files matched the pattern, so the glob was left intact (a literal asterisk, followed by dot-txt).

This can be very annoying, for example when you drive a for-loop using the pathname expansion:

for filename in *.txt; do
  echo "=== BEGIN: $filename ==="
  cat "$filename"
  echo "=== END: $filename ==="
done
When no file name matches the glob, the loop will not only output stupid text ("BEGIN: *.txt"), but also will make the cat-command fail with an error, since no file named *.txt exists.

Now, when the shell option nullglob is set, Bash will remove the entire glob from the command line. In case of the for-loop here, not even one iteration will be done. It just won't run.

So in our first example:

$ shopt -s nullglob
$ echo "Textfiles here:" *.txt
Textfiles here:

and the glob is gone.

Glob characters

For example, to match something beginning with either 'S' or 'K' followed by two numbers, followed by at least 3 more characters:

[SK][0-9][0-9]???*

See also