How to use variable as a path for find command

2019-09-06 19:17发布

问题:

Can someone give me a hint, how I can make the following bash script run properly:

path="/path/"
excludepath="! -path \"/path/to/exclude/*\" "

find "$path" "$excludepath" -name *."txt" -type f

When I try to run it I get:

find: `! -path "/path/to/exclude/*"': No such file or directory

Thank you in advance.

回答1:

Your problem was the fact that "$excludepath" is a single argument, even if it contains spaces. To put several arguments, use an array of strings instead of a string:

excludepath=(! -path "*webshow*")
find "$path" "${excludepath[@]}" -name "*.txt" -type f

This is a bashism, though (people that stumble onto this and don't use bash will need to do something else).