Adding multiple user inputs to one variable in Bash

I am new to bash unix scripts and should know if this is possible. I want to ask the user to enter them several times, and then save this input into 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

therefore, if the user first enters "abc", he adds "abc" to $ userinputs

then upon repeated request for input and user login "123" the script should save it in the same $ userinputs

this would make $ userinput = abc123

+4
source share
2 answers

The usual way to concatenate two lines in Bash:

new_string="$string1$string2"

{} are needed around the variable name only if we have a literal string that may prevent the variable from expanding:

new_string="${string1}literal$string2"

but not

new_string="$string1literal$string2"

+=:

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

$string .


. :

+4

:

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

, , . a="${a}123${b}". . .

, , ${var}, , , - , , , "${var}" (. , - : 1 2 3).

, (, , $REPLY) , :

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

, read - IFS, . " , " - IFS IFS= read -r . . read .

0

Source: https://habr.com/ru/post/1690300/


All Articles