2

This question already has an answer here:

On Ubuntu 14.04, 64 bit, I have set /lib/modules/4.2.0-27-generic/kernel/drivers to be my current directory. I intend to search all files having net present as a sub-string. If I search with a regex of *net*, only the ./net directory is returned as the search result. However, if I specify exact file name, then only it lists out the relevant file (Useless because not always I know the exact file name to cross check).

$ find . -name *net* 
./net
$ find . -name *usbnet* 
./net/usb/usbnet.ko
$ pwd
/lib/modules/4.2.0-27-generic/kernel/drivers

What mistake am I making?

marked as duplicate by Gilles, Jeff Schaller, mdpc, sam, Archemar Jun 30 '16 at 4:22

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

7

Because when you use just *net* (without any quoting or escaping), it will be expanded by the shell as the (existing) net file/directory in the current directory before the find command run. So the command becomes:

find . -name net

As you can see it is just matching net, so usbnet.ko will not be matched.

Also note that, without quoting and escaping, if the pattern does not match (and nullglob and failglob options are disabled), it is treated as is. So for example, for find . -name *net*, if no file name contains net in current directory the pattern find gets is *net*.


So to solve the problem, you need to avoid the shell globbing, to do so you can use quoting or escaping the glob patterns:

find . -name '*net*' 
find . -name "*net*" 
find . -name \*net\* 
  • What I didn't understand is why bash strips off wildcards(*) during expansion (if used without quoting or escaping). – Holmes.Sherlock Jun 29 '16 at 7:10
  • 1
    It is not stripping them, it is using them to match. – matzeri Jun 29 '16 at 7:13
  • 1
    @Holmes.Sherlock bash does not strip off wildcards, do ls *net* and you will see you have only one file named net n that directory. If there are other files e.g. foonetbar, spamnet, then *net* would match them too.. – heemayl Jun 29 '16 at 7:13
  • 1
    A lot of users imagine that the globbing is done in ls. To see what the shell is doing, and break this illusion, do echo *net*. – ctrl-alt-delor Jun 29 '16 at 7:37
  • 2
    and the other point is that when a pattern does not match, then bash does not remove any of the wildcard characters, and find gets the argument *usbnet* with asterisks – glenn jackman Jun 29 '16 at 10:46

Not the answer you're looking for? Browse other questions tagged or ask your own question.