In Is globbing a feature of the shell?

I learned how to use globbing in find command but today i saw a strange behavior.

when i am in any place except the location of my searching i do not need single or double quotes for globbing

$ pwd
$ find / -name *c
it is ok


$ pwd
$ find / -name *c
find: paths must precede expression: proc
Usage: find [-H] [-L] [-P] [-Olevel] [-D help|tree|search|stat|rates|opt|exec] [path...] [expression]

What happen?

  • Guess what letter etc and proc both end with? – Dmitry Grigoryev Sep 26 '16 at 14:04

When you use unquoted (or un-escaped) * i.e. glob token * (any number of characters i.e. any file), the shell expands * to all files in the given directory, in case of *c, all files ending in c. So when you run:

find / -name *c

assuming there are three .c files in the current directory namely foo.c, bar.c, and spam.c, the command actually would run is:

 find / -name foo.c bar.c spam.c

which is an invalid command, as you can see it's using multiple filenames after single -name option. This is what happening when you are at /.

Now, while at /home, presumably there was no *c files present, hence the glob pattern *c will be retained (in bash, this is shell dependent behavior; in bash, you can change the default behavior by nullglob/failglob shell options), so the command find gets is:

 find / -name *c

which is a valid command and expectedly being run.

Now, with find you should quote or escape any shell globbing token, as you want find to interpret (expand) those, not beforehand by the shell. So do any one of:

find / -name '*c'
find / -name "*c"
find / -name \*c
  • your means is first bash see globbing and expand them in current directory if there is not matching it pass it to command?like '*c' or "*c" or *c – Sinoosh Sep 26 '16 at 9:03
  • 1
    @Sinoosh Yes, but not like '*c'/"*c"/\*c, just literally. '*c'/"*c"/\*c will prevent the expansion by shell, so find will do the expansion itself. – heemayl Sep 26 '16 at 9:31
  • 1
    @Sinoosh Basically, using unquoted glob patterns expecting them to be passed to the program is 'playing with fire'. Some shells support options that disable this entirely (nullglob/failglob in bash, nomatch in zsh). – Random832 Sep 26 '16 at 14:12
  • @Random832 sorry to somewhat disagree, but "using unquoted glob patterns expecting them to be passed to the program" is pointing a gun at your feet, and playing with the trigger - that's a more accurate analogy. But then, shooting yourself in your foot speeds up learning! :) – Volker Siegel Sep 26 '16 at 17:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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