arrayslinuxbashshell

How to empty an array in bash script


I am trying to get specific information from a bunch of files. Iterating over a list of files,greping for what I need. I know for sure that each grep will give more than 1 result and I want to store that result in an array. After finishing the work specific to file, I want to erase everything from arrays and start afresh for new file.

files_list=`ls`

for f in $files_list
do
        echo $f
        arr1=`cat $f | grep "abc" | grep "xyz"`
        arr2=`cat $f | grep "pqr" | grep "mno"`
        arr3=`cat $f | grep "df"`
        for ((i=0; i<${#arr1[@]}; ++i)) 
        do
            printf "%s  %s %s\n" "${arr1[i]}" "${arr2[i]}" "${arr3[i]}"
        done
        unset $arr1
        unset $arr2
        unset $arr3
done

So I used unset to empty the array but it's giving error.

line 49: unset: `x': not a valid identifier

I don't want to delete a particular member/index of array but entire array itself. Can anyone tell me how to do it?


Solution

  • unset works with variable names, not the values they keep. So:

    unset arr1
    

    or, if you want to empty it:

    arr1=()