Search code examples
bashquotescommand-substitution

bash command substitution: find command with wildcard in single quotes


I want to dynamically construct a "find" command and see whether it returns anything.

This is the minimised example. In a directory containing files,

find . -name '*'

of course returns the files. But

VAR="find . -name '*'"
$VAR

returns nothing. Looks like a problem of interpretation of quotes. But why?

(The real case is that I want to see whether files with a certain prefix exist. So I intended to use -name '${MYPREFIX}*', capture the output within $(), and test whether the resulting string is empty.)

Apologies if this is trivial. I did spend time to find the answer, but all cases I found were somehow different. Usually, the problem is the shell expanding the wildcard when the find command should do it. Here, the shell does not do any premature expansion, but neither does find, maybe because find receives literal quotes? Thanks for any insight.


Solution

  • eval $VAR
    

    The eval will reinterpret the value of $VAR as a command with arguments.

    Be wary: eval is a powerful but dangerous mechanism.