Search code examples
stringbashshstring-concatenation

Concatenate inputs in string while in loop


I have a variable of sources that is basically a string of comma-separated elements:

SOURCES="a b c d e"

I want the user to input one destination for each of this source, and I want hence to store this input into a string looking like the above but containing the destinations. If I want to assign a=1, b=2... etc, I would have something like this:

echo $DESTINATIONS >>> "1 2 3 4 5"

In order to do the above, I do this:

SOURCES="a b c d e"
DESTINATIONS=""

for src in $SOURCES
do
    echo Input destination to associate to the source $src:
    read dest
    DESTINATIONS=$DESTINATIONS $dest
done

However, if I do an echo on $DESTINATIONS, I find it empty. Moreover, at each loop, my shell tells me:

-bash: = **myInput**: command not found

Any idea where I'm doing wrong?


Solution

  • SOURCES="a b c d e"
    DESTINATIONS=""
    
    for src in $SOURCES
    do
        echo Input destination to associate to the source $src:
        read dest
        DESTINATIONS+=" ${dest}"
    done
    echo $DESTINATIONS
    

    works for me.