Bash: Is there a way to easily break a large array into smaller ones?

arrays, bash, split

Solution

If you have `bash` version 3.2 or higher, you can do it using the new "subelement" syntax (`${bigArray[@]:index_of_first_element:element_count}`), but be careful — if the element values have any spaces in them, this could break horribly without preprocessing.

So the idea is along the lines of:

cnt="${#bigArray[@]}"
let cnt1="$cnt/2"
let cnt2="$cnt - $cnt1 - 1"
# this way we remove the rounding error if the count was odd and account for 0-based indexing

smallArray=( "${bigArray[@]:0:$cnt1}" )
secondSmallArray=( "${bigArray[@]:$cnt1:$cnt2}" )

Problem

I was wondering if there is an easy way in bash to break up a large array into several smaller ones. I currently am thinking something like this: ``` for ((i = 0; i<= (bigArrayLength/2); i++)) do bigArray[i] = smallArray[i] done for ((i = (bigArrayLength/2); i <=bigArrayLength; i++)) do bigArray[i] = secondSmallArray[i] done ``` But there has to be a better way to go about it. Any suggestions? Thanks!

Original source