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?
Python concatenate strings in for loop To concatenate strings we will use for loop, and the “+ ” operator is the most common way to concatenate strings in python.
The answer is: using '+' operator. Alternatively, you can use the String method String concat(String) : http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#concat(java.lang.String).
Concatenation of two Strings If you concatenate Stings in loops for each iteration a new intermediate object is created in the String constant pool. This is not recommended as it causes memory issues.
You concatenate strings by using the + operator. For string literals and string constants, concatenation occurs at compile time; no run-time concatenation occurs. For string variables, concatenation occurs only at run time.
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.
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"
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[@]}"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With