Search code examples
bashshellloopsassociative-array

Clear part of associative array


Must I use a loop to clear some data in an associative array, or is there a faster & better option?

currently I'm using:

until [[ $ploop1 -eq 99 ]]; do  ##do044
    ((++ploop1))
    hnr[$ploop1,2]=0
    hnr[$ploop1,3]=0
    hnr[$ploop1,4]=0
    hnr[$ploop1,5]=0
done  ##do044

Observe that ,0 and,1 shouldn't be cleared


Solution

  • Consolidating my comments into one area ...

    OP has mentioned 'clear the data' but is really setting the array elements to 0 (zero). If OP has a list of numbers to process then something like the following should also work:

    until [[ $ploop1 -eq 99 ]]; do
        ((++ploop1))
        for x in {2..5}            # or `x in 2 3 4 5` or `x in {2..4} 5` or ...
        do
            hnr[$ploop1,$x]=0
        done
    done
    

    If OP doesn't mind using eval this can be shortened a bit to:

    until [[ $ploop1 -eq 99 ]]; do
        ((++ploop1))
        eval hnr[$ploop1,{2..5}]=0 
    done
    

    Now, if OP wants to clear the elements as in remove the elements, then this should work ...

    until [[ $ploop1 -eq 99 ]]; do
        ((++ploop1))
        unset hnr[$ploop1,{2..5}]
    done
    

    ... and as long as the unset is issued against array elements and NOT the array (ie, unset hnr) then the array declaration remains intact/valid, ie, no need to redeclare -A the array.


    Adding Philippe's question/comment:

    If the entire purpose of OPs loop is to just unset the array elements then the following should eliminate the need for a loop:

    unset hnr[{0..99},{2..5}]
    

    NOTE: OP can adjust the numbers based on actual ranges in use ...