can't seem to populate bash array with new elements using '+=' operator

1

Like the title says. Trying to populate an array from zenity checklist output. Here is the function I want to run, but fails:

function fSongType() {
    mType=$(zenity --list --title "Random song list generator" --text "Enter path from which to randomly choose songs:" --width="300" --height="360" --radiolist --column "Pick" --column "Music type" --print-column=2 FALSE All FALSE Baby FALSE Children FALSE "Easy Peasy" FALSE Holiday FALSE Instrumental FALSE "Rock Classics" TRUE "Rock Next Gen" FALSE "Rock Next Gen Heavy" FALSE "Rock Next Gen Light" FALSE "Rock Pop" FALSE Spiritual FALSE Thai|sed -r 's/[ ]{1,}//g') ; echo "\$mType: ${mType}"

    # create an array for the output of user checklist input returned to var '$mType"
    mTypeAr=()
    cntr=0
    until [[ -z "$mType" ]] ; do
        mTypeAr+=$(echo "$mType"|sed -r 's/^[|]{0,1}([a-zA-Z]*)[|]{0,1}.*$/\1/') ; echo "\$mTypeAri[$cntr]: ${mTypeAr[$cntr]}"
        mType=$(echo "$mType"|sed -r 's/^[|]{0,1}[a-zA-Z]*(|.*)$/\1/') ; echo "\$mType: ${mType}"
        ((cntr++))
    done
}

Subsequent terminal output:

${mTypeAr[0]}: Instrumental|RockClassics|RockNextGen|RockClassics|RockNextGen|RockNextGenInstrumentalRockClassics|RockNextGenRockClassicsRockNextGenRockNextGenInstrumentalRockClassics|RockNextGen
$mType: |RockClassics|RockNextGen
${mTypeAr[1]}: 
$mType: |RockNextGen
${mTypeAr[2]}: 
$mType:

So for reasons unknown (to me) the zenity output is all assigned to first element in array. But if I modify the array assignment using the '$cntr' var instead then the array elements are populated as expected.

# create an array for the output of user checklist input returned to var '$mType"
    mTypeAr=()
    cntr=0
    until [[ -z "$mType" ]] ; do
        mTypeAr["$cntr"]=$(echo "$mType"|sed -r 's/^[|]{0,1}([a-zA-Z]*)[|]{0,1}.*$/\1/') ; echo "\$mTypeAri[$cntr]: ${mTypeAr[$cntr]}"
        mType=$(echo "$mType"|sed -r 's/^[|]{0,1}[a-zA-Z]*(|.*)$/\1/') ; echo "\$mType: ${mType}"
        ((cntr++))
    done

Subsequent terminal output:

$mType: Instrumental|RockClassics|RockNextGen
${mTypeAr[0]}: Instrumental
$mType: |RockClassics|RockNextGen
${mTypeAr[1]}: RockClassics
$mType: |RockNextGen
${mTypeAr[2]}: RockNextGen
$mType:

I want to lose the '$cntr' var and echo's once everything is working as expected. I am sure the problem is something obvious that I am missing; but dog gone if I can't see it for looking at it. Any help appreciated.

nanker

Posted 2014-02-26T21:58:29.087

Reputation: 183

Answers

0

array+=string appends "string" to the first element of array; to add it as a new element use array+=(string) instead. In your function, this means using:

mTypeAr+=($(echo "$mType"|sed -r 's/^[|]{0,1}([a-zA-Z]*)[|]{0,1}.*$/\1/'))

Gordon Davisson

Posted 2014-02-26T21:58:29.087

Reputation: 28 538