I am writing a bash script to count number of files given user parameters of path and exclude path. I construct a command using my bash script, where the last few line looks like this
command="find . $exclude | wc -l"
echo $command
So for example, it might result in
find .
Or if I set exclude to be '-not \( -path "./special_dir" -prune \)', then the command would be
find . -not \( -path "./special_directory" -prune \)
Both commands I can copy and paste into a command line and everything is fine.
The problem comes when I try to run it.
exclude=""
command="find $. $exclude | wc -l"
echo $command
results=$($command)
echo "result=$results"
Above works, but the snippet below would fail.
exclude='-not \( -path "./special_dir" -prune \)'
command="find $. $exclude | wc -l"
echo $command
results=$($command)
echo "result=$results"
returns
find . -not \( -path "./special_dir" -prune \) | wc -l
find: paths must precede expression: \(
Usage: find [-H] [-L] [-P] [-Olevel] [-D help|tree|search|stat|rates|opt|exec] [path...] [expression]
But if I use eval to run command, even the exclude is fine
exclude='-not \( -path "./special_dir" -prune \)'
command="find $. $exclude | wc -l"
echo $command
results=$(eval $command)
echo "result=$results"
Returns
find . -not \( -path "./special_dir" -prune \) | wc -l
result=872
I don't understand what's wrong with just running the command with exclude directory. My guess is it has to do some with kind of escaping special characters?