Dinesh
Dinesh

Reputation: 4561

find command fusses on -exec arg

I am trying to build and run a find command from a script. But I get a very cryptic error message from find. The following basically sums up how I build the command line and run it

$ xx="find . -name 'p*' -mmin +10 -exec echo {} \\;"
$ echo "$xx" #.....and I get the same print from echo $xx
find . -name 'p*' -mmin +10 -exec echo {} \;
$ $xx
find: missing argument to `-exec'
$ find . -name 'p*' -mmin +10 -exec echo {} \;
./p2.sh
./p1.sh
$ read xx
find . -name 'p*' -mmin +2 -exec echo {} \\;
$ $xx
find: missing argument to `-exec'

I am stuck and will appreciate your help. I am also wondering what's causing this. I am using bash 3.2.51 on SLES.

The actual command I want to execute is a little bit longer but I used echo here just to illustrate.

Thanks Dinesh

Upvotes: 0

Views: 194

Answers (1)

rici
rici

Reputation: 241711

Trying to store complicated commands in bash variables and then evaluate the variables pretty well never works.

If you need to build a command in pieces, use an array. See this useful Bash FAQ: I'm trying to put a command in a variable, but the complex cases always fail!.

Here's the basic strategy:

# Make an array
declare -a findcmd=(find .)
# Add some arguments
findcmd+=(-name 'p*')
findcmd+=(-mmin +10)
findcmd+=(-exec echo {} \;)
# Run the command
"${findcmd[@]}"

You need to understand how bash quoting works. Remember that the quoting (and de-quoting) only happens once, when you type the command (or when bash reads it from a script file). Quotes which get into the values of variables are just ordinary characters.

If you're experimenting with set -x, remember also that set -x inserts quotes in order to remove ambiguities. These quotes are not part of the variables. While that is clearly essential, it seems to be confusing to programmers who are not familiar with the bash execution model.

Upvotes: 5

Related Questions