Home > Mobile >  why result set value not stored in arraylist in shell script
why result set value not stored in arraylist in shell script

Time:07-22

sample code below

psql -h $host -U postgres -d postgres -At -c "select partner_country_id as country , case when (threshold is null) then global_threshold else threshold end as threshold from ra_country_day_threshold " \
    | while read -a Record 
    do
        arrIN=(${Record[0]//|/ })
        col1=${arrIN[0]}
        col2=${arrIN[1]}
        country_array["$col1"]="$col2"
        echo "Col1:$col1 Col2:$col2"
done
echo "Elements:${country_array[@]}"
echo "length: ${#country_array[@]}" 

Result

empty elements and length 0

CodePudding user response:

The answer is simple, while command create a subprocess with its own context, if you create a new variable in that context, it will not be accessible outside of it. Meaning the variable will not be accessible when you are outside the loop.

My suggestion is that you store the result inside a temporary file that will be available within all your script, then outside your loop, read that file.

  • Related