I'm trying to build a long command involving find
. I have an array of directories that I want to ignore, and I want to format this directory into the command.
Basically, I want to transform this array:
declare -a ignore=(archive crl cfg)
into this:
-o -path "$dir/archive" -prune -o -path "$dir/crl" -prune -o -path "$dir/cfg" -prune
This way, I can simply add directories to the array, and the find
command will adjust accordingly.
So far, I figured out how to prepend or append using
${ignore[@]/#/-o -path \"\$dir/}
${ignore[@]/%/\" -prune}
But I don't know how to combine these and simultaneously prepend and append to each element of an array.
You cannot do it simultaneously easily. Fortunately, you do not need to:
ignore=( archive crl cfg )
ignore=( "${ignore[@]/%/\" -prune}" )
ignore=( "${ignore[@]/#/-o -path \"\$dir/}" )
echo ${ignore[@]}
Note the parentheses and double quotes - they make sure the array contains three elements after each substitution, even if there are spaces involved.
Have a look at printf
, which does the job as well:
printf -- '-o -path "$dir/%s" -prune ' ${ignore[@]}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With