'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 1:[1]
$ string="test"
$ string="${string}test2"
$ echo $string
testtest2
Solution 2:[2]
#!/bin/bash
message="some text"
message="$message add some more"
echo $message
some text add some more
Solution 3:[3]
teststr=$'test1\n'
teststr+=$'test2\n'
echo "$teststr"
Solution 4:[4]
VAR=$VAR"$VARTOADD(STRING)"
echo $VAR
Solution 5:[5]
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"
Solution 6:[6]
#!/bin/bash
msg1=${1} #First Parameter
msg2=${2} #Second Parameter
concatString=$msg1"$msg2" #Concatenated String
concatString2="$msg1$msg2"
echo $concatString
echo $concatString2
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ghostdog74 |
| Solution 2 | Jim |
| Solution 3 | Ignacio Vazquez-Abrams |
| Solution 4 | |
| Solution 5 | n1ce-0ne |
| Solution 6 | Danila Ganchar |
