Concatenating inputs into a string during a loop

I have a sources variable which is basically a comma separated string of items:

SOURCES="a b c d e"

      

I want the user to enter one destination for each of this source, and so I want to store that input on a line similar to the one above, but containing the destinations. If I want to assign a = 1, b = 2 ... etc., I will have something like this:

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

      

To do this, 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 echo

on $DESTINATIONS

, I find it empty. Moreover, in every loop, my shell tells me:

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

      

Any idea where I am doing wrong?

+3


source to share


4 answers


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.

+3


source


You should be using an array, not a delimited string.



sources=(a b c d e)

for src in "${sources[@]}"
do
    read -p "Input destination to associate to the source $src" dest
    destinations+=( "$dest" )
done

printf '%s\n' "${destinations[@]}"

      

+3


source


The most obvious problem with your code is this line:

DESTINATIONS=$DESTINATIONS $dest

      

Rather, the above line should be written:

DESTINATIONS="$DESTINATIONS $dest"

      

Problem: you execute $ dest and pass the environment DESTINATIONS = $ DESTINATIONS. This hopefully explains the error messages you are seeing.

I tried my code with the quotes I suggested and it works great.

+2


source


Q: What's wrong? A: Don't use quotation marks where necessary.

If you use an unquoted space, it will be used by the shell to separate the string.

Using:

DESTINATIONS=$DESTINATIONS $dest

      

The $ dest variable is understood by the shell as an executable command, so you get the error:

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

      

To fix the problem, just include a space.
There are several ways to do this:

DESTINATIONS=$DESTINATIONS" "$dest
DESTINATIONS=$DESTINATIONS' '$dest
DESTINATIONS="$DESTINATIONS"' '"$dest"
DESTINATIONS="$DESTINATIONS $dest"

      

The latter option is probably the simplest and also the best overall.
You can also use this syntax (since bash 3.1-alpha1):

    DESTINATIONS+=" $dest"

      

Also please! Specify your other extensions:

echo "$DESTINATIONS"

      

+1


source







All Articles