How do you append to an already existing string?

StringBashShellString Concatenation

String Problem Overview


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

String Solutions


Solution 1 - String

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

Solution 2 - String

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

Solution 3 - String

#!/bin/bash
message="some text"
message="$message add some more"

echo $message

some text add some more

Solution 4 - String

teststr=$'test1\n'
teststr+=$'test2\n'
echo "$teststr"

Solution 5 - String

VAR=$VAR"$VARTOADD(STRING)"   
echo $VAR

Solution 6 - String

#!/bin/bash

msg1=${1} #First Parameter
msg2=${2} #Second Parameter

concatString=$msg1"$msg2" #Concatenated String
concatString2="$msg1$msg2"

echo $concatString 
echo $concatString2

Solution 7 - String

thank-you Ignacio Vazquez-Abrams

i adapted slightly for better ease of use :)

placed at top of script

NEW_LINE=$'\n'

then to use easily with other variables

variable1="test1"
variable2="test2"

DESCRIPTION="$variable1$NEW_LINE$variable2$NEW_LINE"

OR to append thank-you William Pursell

DESCRIPTION="$variable1$NEW_LINE"
DESCRIPTION+="$variable2$NEW_LINE"

echo "$DESCRIPTION"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMintView Question on Stackoverflow
Solution 1 - StringWilliam PursellView Answer on Stackoverflow
Solution 2 - Stringghostdog74View Answer on Stackoverflow
Solution 3 - StringJimView Answer on Stackoverflow
Solution 4 - StringIgnacio Vazquez-AbramsView Answer on Stackoverflow
Solution 5 - StringManuelsenView Answer on Stackoverflow
Solution 6 - StringAdityaView Answer on Stackoverflow
Solution 7 - Stringn1ce-0neView Answer on Stackoverflow