1

Is there a way to prevent wildcard expansion on the find command so that the following would work?

find . -iname "foo [bar]"

As pointed out here, I tried running set -f, set -o noglob and setopt noglob just before find but it didn't work.

It's a bash script and I'm using Ubuntu 10.04.

I know I could just escape the wildcard characters but I fear I might leave one out.

  • 1
    What do you means by “would work”? The command you posted does work. If it doesn't do what you want, tell us what you want it to do. – Gilles 'SO- stop being evil' Dec 8 '13 at 22:47
2

As @njsg already said, the problem is caused by find, not the shell: The double quotes you are using are already protecting your expression from the shell; it is passed to find unmodified.

The problem is that find treats the argument to -name and -iname as a pattern. The only way to suppress that would be to use a find option that does not treat its argument as a pattern. But find has no such thing, according to my manual page, so what you want cannot be done. The best you can do is enhance your script to escape the brackets automatically, before passing them to find. The following funny-looking sed substitution will do that for you:

echo "foo [bar]" | sed 's/[][]/\\&/g'

Will print: foo \[bar\]

  • Thanks, alexis. I'll accept your answer for being the most complete and pushing me to a good path to do all the escaping I have to do. – lsborg Dec 9 '13 at 15:07
  • Good answer. Certainly GNU find has no such option (and I don't recall anybody ever asking for it). – James Youngman Dec 9 '13 at 22:55
4

The problem is not with the shell, but with find. The argument to -name and -iname is a pattern itself. [bar] will mean b, a or r to find. Try just escaping the square brackets, that is:

find . -iname "foo \[bar\]"

(Edit: With this, you are not escaping them at the shell level, but passing the backslashes to find.)

  • Thanks, njsg. I'm looking for a solution that does not depends on escaping the wildcards. – lsborg Dec 8 '13 at 21:29
  • Ah, right, I missed that, sorry. As @alexis said, this largely depends on whether find supports it. And, from what @alexis said, it does not seem to. I'd indeed suggest alexis' sed idea. – njsg Dec 8 '13 at 23:41
-1

You can use single quotes to prevent expansion.

find . -iname 'foo [bar]'
  • Thanks for the prompt answer, Zelda. It works with ls but not with find. Could you recheck this just to be sure? I just ran find. – lsborg Dec 8 '13 at 18:50
  • Sorry, this indeed does not seem to work as I was sure it was going to, sorry. – Zelda Dec 8 '13 at 19:31

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.