Concatenate inputs in string while in loop

安稳与你 提交于 2021-01-27 02:54:11

问题


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?


回答1:


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.




回答2:


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:


The most obvious issue with your code is this line:

DESTINATIONS=$DESTINATIONS $dest

Rather, the above line should be written:

DESTINATIONS="$DESTINATIONS $dest"

The issue: You are executing $dest and passing an environment of DESTINATIONS=$DESTINATIONS. This hopefully explains the error messages you are seeing.

I tried your code out with the quotes I've suggested and it works fine.




回答4:


Q: What is wrong?
A: Not using quotes where needed.

If you use an space un-quoted it will be used by the shell to split the line.

When you use:

DESTINATIONS=$DESTINATIONS $dest

The variable $dest is understood by the shell as a command to execute, that's why you are getting the error:

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

To solve the issue, just quote the space.
There are several ways to do that:

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

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

    DESTINATIONS+=" $dest"

Also, please!, quote your other expansions:

echo "$DESTINATIONS"


来源:https://stackoverflow.com/questions/42934198/concatenate-inputs-in-string-while-in-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!