Wednesday, 11 November 2009

Null glob

nullglob : (special character * is called a glob which expands to filenames or dirs etc..)

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 ==="

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.

No comments:

Post a Comment

Tweets by @sriramperumalla