8

I thought the wildcard * in the command find . -name *foo* is replaced by bash, and yet the command works unless *foo* matches something in the current directory, then it doesn't. It's confusing.

1
  • 3
    Note: If you replace the find . -name *foo* with find . -name '*foo*' it will allow the wildcard matches to work as expected.
    – Bill
    Jul 29, 2011 at 22:01

2 Answers 2

14

If bash can't find a match, it passes the literal string to the application with *s unexpanded. For example:

$ ls
foo

$ cat /tmp/test
echo $1

$ /tmp/test *foo*
foo

$ /tmp/test *bar*
*bar*

bash expanded *foo* because it matched, but passed *bar* directly because it didn't. The nullglob option will tell bash to resolve non-matching patterns to the empty string instead:

$ shopt -s nullglob
$ /tmp/test *bar*

$
2
  • 1
    A little comment to say that zsh has not the same default behavior, it returns an error: zsh: no matches found. Jul 29, 2011 at 19:00
  • zsh has no_nomatch to trigger this behavior.
    – chx
    Oct 24, 2014 at 5:45
5

If you want find to get the unexpanded string, then you could quote it or protect the wildcards with backslashes.

$ ls
foo

$ cat /tmp/test
echo $1

$ /tmp/test '*foo*'
*foo*

$ /tmp/test \*foo\*
*foo*

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .