Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash arrays: appending and prepending to each element in array

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.

like image 706
jh314 Avatar asked Jul 11 '13 20:07

jh314


2 Answers

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.

like image 174
choroba Avatar answered Sep 28 '22 01:09

choroba


Have a look at printf, which does the job as well:

printf -- '-o -path "$dir/%s" -prune ' ${ignore[@]}

like image 43
setempler Avatar answered Sep 28 '22 00:09

setempler