Skip to content
Advertisement

Glob that doesn’t match anything expands to itself, rather than to nothing

I want to iterate over the files in a folder of a special type (like .test):

So I wrote a little script names for_loop:

JavaScript

After (chmod +x for_loop) I can start it with ./for_loop.

If there are .test-files, everthing is fine, BUT if there is no file in the folder that matches *.test, the for-loop is still executed once. In this case the output looks like:

JavaScript

But I thought that if there were no files in the folder that match the glob pattern, there would be no output. Why is this not the case?

Advertisement

Answer

This is the default behaviour.

to get rid of it, enable nullglob:

JavaScript

From Greg’s Wiki – nullglob:

nullglob expands non-matching globs to zero arguments, rather than to themselves.

Without nullglob, the glob would expand to a literal * in an empty directory, resulting in an erroneous count of 1.

Or use zsh, which has this glob enabled by default!

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement