12

I read many questions and answers like this and this one

I know wildcards are expanded by the shell before running a command and they are a feature of the shell. Also wildcards work with those commands that can accept many arguments. In find . -name *.rb if we have more than one file in the current directory find will give us an error because find cannot accept multiple arguments and the ways to solve this are:

find . -name "*.rb"
find . -name '*.rb'
find . -name \*.rb

We escape the asterisk and prevent expansion by the shell but wildcards are a feature of the shell; when we escape the asterisk shell does not know about its meaning, and it should find a file named *.rb, so how is the asterisk being expanded in this case?

21

Yes, the shell understands * as all files with any characters in the directory and *.rb as all files with any characters and ending .rb, and expands it as such.

The find command itself accepts globbing.

If you don't quote the * then the shell will expand it before the find command sees its argument, so instead of a glob *.rb passed to find, the names of all files matching the glob in the directory will be passed to find, and find will try to interpret them as arguments, which will likely result in an error, or at least not what you want (it will work correctly only if there are no matching files in the current directory)

| improve this answer | |
  • thank you,it means we say to shell it is not a glob but some commands can expand wildcards? or can we say if we have a shell without understanding about globbing those commands knows about globbing can expand them? – Sinoosh Sep 22 '16 at 8:34
  • 5
    if the * is quoted, then the shell won't expand it, and the argument including the glob is passed to the command that can understand the glob - it's the same for any commands that accept regex which should always be quoted... – Zanna Sep 22 '16 at 8:39
  • 1
    My pleasure ^_^ – Zanna Sep 22 '16 at 8:49
  • 7
    @Sinoosh: Note that not all commands understand glob syntax. It just happens to be a feature of find – slebetman Sep 22 '16 at 10:26
  • 1
    @Sinoosh Find isn't really "expanding" the wildcard, it's using it as a test to match each filename it encounters. There are a (very) few commands that do expand wildcards in the conventional sense - unzip and 7z can use it to open multiple archives (when their arguments are normally of a form "[archive filename single argument] [list of files to extract]") for example. – Random832 Sep 22 '16 at 13:33

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.