How do you append to an already existing string?


Question

I want append to a string so that every time I loop over it will add say "test" to the string.

Like in PHP you would do:

$teststr = "test1\n"
$teststr .= "test2\n"
echo = "$teststr"

echos:

test1
test2

But I need to do this in a shell script

1
102
10/25/2016 5:27:10 PM

Accepted Answer

In classic sh, you have to do something like:

s=test1
s="${s}test2"

(there are lots of variations on that theme, like s="$s""test2")

In bash, you can use +=:

s=test1
s+=test2
183
2/17/2017 10:23:16 AM

$ string="test"
$ string="${string}test2"
$ echo $string
testtest2

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon