'Passing a command to 'find -exec' through a variable does not work
given a directory $HOME/foo/ with files in it.
the command:
find $HOME/foo -type f -exec md5deep -bre {} \;
works fine and hashes the files.
but, creating a variable for -exec does not seem to work:
md5="md5deep -bre"
find $HOME/foo -type f -exec "$md5" {} \;
returns: find: md5deep -bre: No such file or directory
why?
Solution 1:[1]
Use an array.
md5Cmd=(md5deep -bre)
find "$HOME/foo" -type f -exec "${md5Cmd[@]}" {} \;
Solution 2:[2]
Better still, make the whole -exec statement optional:
md5Cmd=( -exec md5deep -bre {} \; )
find "$HOME/foo" -type f "${md5Cmd[@]}"
Solution 3:[3]
I have found the syntax for find -exec a bit weird (with several pitfalls as the ones @codeforester has mentioned).
So, as an alternative, i tend to separate the search part from the action part by piping the output of find (or grep) to a proper xargs process.
For example, i find it more readable (-n1 for using exactly 1 argument per command):
find $HOME/foo -type f | xargs -n1 md5deep -bre
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | chepner |
| Solution 2 | markling |
| Solution 3 | Michail Alexakis |
