Home > front end >  Array created inside function can't be accessed after function exit
Array created inside function can't be accessed after function exit

Time:08-09

I have a problem with arrays. I wrote code

#!/bin/bash

function getrow() {
    OLDIFS=$IFS;
    IFS=";";
    declare -A data;
    #arr1=($(nl -v 0 data.csv | awk '{print $1}'));
    n=0;

    while read bronum libID BrID
    do
        data[$n,0] ="$n";
        data[$n,1] ="$bronum";
        data[$n,2] ="$libID";
        data[$n,3] ="${BrID/$'\r'/}";
        echo ${!data[@]};
        echo ${#data[@]};
        echo ${data[@]};
        sleep 7;
        ((n  ))
    done < data.csv

    IFS=$OLDIFS;
    ((n--));
}

#-------BEGIN-----
getrow;
echo ${!data[@]};
echo ${#data[@]};
echo ${data[@]};
sleep 7;

exit 0;

File data.csv has structure like:

125099428;OSCEOLA1;O-BVL
125099428;OSCEOLA1;O-CEL
125099428;OSCEOLA1;O-CEN
125099428;OSCEOLA1;O-POI
125099428;OSCEOLA1;O-STC

When I print the array elements in the functions - a get correct output and array structure but when I try output array in program - I get nothing. I do not understand why I do not get all array outside the function.

CodePudding user response:

A few different options available ...

  • declare the array outside of the function
  • declare an array outside of the function, pass the array name to the function, have the function use a nameref to populate the array
  • declare the array as global (-g)

The 3rd option means:

# replace:

declare -A data

# with:

declare -Ag data

Take for a test drive:

$ getrow
... assorted output from the echo calls ...

$ typeset -p data
declare -A data=([1,1]="125099428" [1,0]="1" [1,3]="O-CEL" [1,2]="OSCEOLA1" [0,0]="0" [0,1]="125099428" [0,2]="OSCEOLA1" [0,3]="O-BVL" [3,3]="O-POI" [3,2]="OSCEOLA1" [3,1]="125099428" [3,0]="3" [2,2]="OSCEOLA1" [2,3]="O-CEN" [2,0]="2" [2,1]="125099428" [4,0]="4" [4,1]="125099428" [4,2]="OSCEOLA1" [4,3]="O-STC" )
  • Related