Search code examples
stringbashshellstring-concatenation

How do you append to an already existing string?


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

Like in PHP you would do:

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

Returns:

test1
test2

But I need to do this in a shell script


Solution

  • 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