Bash arrays: appending and prepending to each element in array

arrays, bash, formatting, shell

Solution

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.

Problem

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.

Original source