Sign up ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

Instead of displaying (or writing) every result once generated, i designed an Array based Buffer to store data and write it whenever the line counter reaches a MAX value. Here is the script :

#Buffer Management
function bufferReset (){
    unset BUFFERVAR
function bufferAppend () {
    (( BUFFERCURSOR++ ))
function bufferDisplay () {
    for ((i=1;i<=$BUFFERCURSOR;i++)); do printf "%s\n" "${BUFFERVAR[$i]}" ; done
#Buffer Management End:
for ((i=1;i<=8;i++)) ; do
    line=`printf "%3s" "$i ==> $(echo $i | md5sum|awk '{print $1}')"` #Example of a string to append
    bufferAppend "$line"
    if [ "$BUFFERCURSOR" == "$BUFFERMAXSIZE" ] ;    then
# Display remaining elements in the "buffer"

So the output is :

1 ==> b026324c6904b2a9cb4b88d6d61c81d1
2 ==> 26ab0db90d72e28ad0ba1e22ee510510
3 ==> 6d7fce9fee471194aa8b5b6e47267f03
4 ==> 48a24b70a0b376535542b996af517398
5 ==> 1dcca23355272056f04fe8bf20edfce0
7 ==> 84bc3da1b3e33a18e8d5e1bdd7a18d7a
8 ==> c30f7472766d25af1dc80b3ffc9a58c7

Why the 6th element is skipped ?

share|improve this question
Replacing the bufferDisplay function code by printf "%s\n" "${BUFFERVAR[@]}" solves the problem. But still dont know why !! – Slyx Feb 4 '14 at 3:15

1 Answer 1

up vote 6 down vote accepted

The problem can easily be seen by starting the script as

bash -vx ./script

You use the same variable in the main program and in a function which is a really bad idea. bufferDisplay leaves i at value 6 after which the i++ of the main loop is executed.

The best way to avoid this is to use a separate name space in all functions. Every variable in a function which is not intentionally the one from the outer name space must be declared like

local i

You could use different names, too; especially with such a small propgram. But the local approach is less error-prone.

share|improve this answer
+1 vote for the -vx bash option :) ! – Slyx Feb 4 '14 at 3:38

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.