4

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

2 Answers 2

5

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:

Sign up to request clarification or add additional context in comments.

2 Comments

can I use this in a while loop to keep asking for the user's input until they enter a certain character like * and all the users input are saved in just one variable?
Yes, @M.Azeem, you could do that.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.