A strange behavior for globbing in find command
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
/home
$ find / -name *c
...
it is ok
but
$ 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?
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