M.Azeem
M.Azeem

Reputation: 43

Adding multiple user inputs into one variable in Bash

I am fairly new to unix bash scripting and need to know if this is possible. I want to ask user for their input multiple times and then store that input in to one variable.

userinputs=   #nothing at the start

read string
<code to add $string to $userinputs>
read string
<code to add $string to $userinputs> #this should add this input along with the other input

so if the user enters "abc" when asked first time, it add's "abc" in $userinputs

then when asked again for the input and the user enters "123" the script should store it in the same $userinputs

this would make the $userinput=abc123

Upvotes: 4

Views: 2819

Answers (2)

codeforester
codeforester

Reputation: 43109

The usual way to concat two strings in Bash is:

new_string="$string1$string2"

{} are needed around the variable name only if we have a literal string that can obstruct the variable expansion:

new_string="${string1}literal$string2"

rather than

new_string="$string1literal$string2"

You can also use the += operator:

userinputs=
read string
userinputs+="$string"
read string
userinputs+="$string"

Double quoting $string is optional in this case.


See also:

Upvotes: 5

Zac B
Zac B

Reputation: 4232

You can concatentate variables and store multiple strings in the same one like so:

foo=abc
echo $foo # prints 'abc'
bar=123
foo="${foo}${bar}"
echo $foo # prints 'abc123'

You can use the other variables, or the same variable, when assigning to a variable, e.g. a="${a}123${b}". See this question for more info.

You don't have to quote the strings you're assigning to, or do the ${var} syntax, but learning when to quote and not to quote is a surprisingly nuanced art, so it's often better to be safe than sorry, and the "${var}" syntax in double quotes is usually the safest approach (see any of these links for more than you ever wanted to know: 1 2 3).

Anyway, you should read into a temporary variable (read, by default, reads into $REPLY) and concatentate that onto your main variable, like so:

allinput=
read # captures user input into $REPLY
allinput="${REPLY}"
read
allinput="${allinput}${REPLY}"

Beware that the read command behaves very differently depending on supplied switches and the value of the IFS global variable, especially in the face of unusual input with special characters. A common "just do what I mean" choice is to empty out IFS via IFS= and use read -r to capture input. See the read builtin documentation for more info.

Upvotes: 1

Related Questions