Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 846
gkr2d2 Avatar asked Apr 11 '19 07:04

gkr2d2


People also ask

How check array is empty or not in shell script?

To check if a array is empty or not, we can use the arithmetic expansion syntax (( )) in Bash. In the example above, this syntax ${#arr[@]} returns the total number of elements in an array.

How do I echo an array in bash?

How to Echo a Bash Array? To echo an array, use the format echo ${Array[0]}. Array is your array name, and 0 is the index or the key if you are echoing an associative array. You can also use @ or * symbols instead of an index to print the entire array.

How do I remove a string from an array in bash?

To really remove an exact item, you need to walk through the array, comparing the target to each element, and using unset to delete an exact match. Note that if you do this, and one or more elements is removed, the indices will no longer be a continuous sequence of integers.

How do you empty a variable in bash?

Return true if a bash variable is unset or set to the empty string: if [ -z "$var" ]; Another option: [ -z "$var" ] && echo "Empty" Determine if a bash variable is empty: [[ ! -z "$var" ]] && echo "Not empty" || echo "Empty"


1 Answers

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

unset arr1

or, if you want to empty it:

arr1=()
like image 173
oguz ismail Avatar answered Oct 11 '22 19:10

oguz ismail