Search code examples
arraysbashunsetarray-splice

Bash: Array has more elements than specified


I am making a shell script to manipulate n number of files at a time. The n files are stored in an array. However past the first iteration of the while loop, the arrays become larger than n.

i.e. If I run the script on 695 total files, the array holds 100 files then holds 200, 300, 395, 295, and lastly 195 in the while loop.

shopt -s nullglob
file_arr=(*.extension)
len_file_arr=${#file_arr[@]}
count_first=0
count_last=100

while (("$count_last" <= "$len_file_arr"))
do
        tf_array=("${file_arr[@]:${count_first}:${count_last}}")
        tf_comma_list=$(IFS=,; echo "${tf_array[@]}")
        echo ${#tf_array[@]}
        # manipulation files
        count_first=$((count_first+100))
        count_last=$((count_last+100))
        unset -v 'tf_array'
done
tf_array=("${file_arr[@]:${count_first}:${len_file_arr}}")
# manipulate left over files

I believe unset is not functioning the way I expect it to. However, the array after the unset command is empty, and I have not been able to find an explanation. What is the reason for this array behavior and how do I fix it?


Solution

  • bash array slicing has this syntax:

    ${array_name[@]:start:count}
    

    Not

    ${array_name[@]:start:end}
    

    You should not increment the count_last like you did in this line:

        count_last=$((count_last+100))
    

    and change the while loop condition. Or, change

        tf_array=("${file_arr[@]:${count_first}:${count_last}}")
    

    to

        tf_array=("${file_arr[@]:${count_first}:100}")