0

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?

2
  • do your filenames have white-space embedded in the names? (probably not, but trying to eliminate an obvious problem). Good luck. Commented Jun 25, 2016 at 3:20
  • @shellter: Nope. They are free of white-space. Either CamelCase or have "_" to make file names more readable. Although, I thought the quoting would avoid white-space problems if there was any. Commented Jun 25, 2016 at 4:48

1 Answer 1

2

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}")
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.