How do you append to an already existing string?
Asked Answered
B

7

153

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

Berwickupontweed answered 12/2, 2010 at 6:51 Comment(0)
C
270

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
Congeries answered 12/2, 2010 at 7:16 Comment(0)
S
34
$ string="test"
$ string="${string}test2"
$ echo $string
testtest2
Seafowl answered 12/2, 2010 at 6:53 Comment(0)
M
16
teststr=$'test1\n'
teststr+=$'test2\n'
echo "$teststr"
Morality answered 12/2, 2010 at 6:52 Comment(0)
A
16
#!/bin/bash
message="some text"
message="$message add some more"

echo $message

some text add some more

Anastrophe answered 16/2, 2010 at 20:36 Comment(0)
M
3
VAR=$VAR"$VARTOADD(STRING)"   
echo $VAR
Mcatee answered 9/9, 2014 at 10:40 Comment(0)
E
2

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"
Earthly answered 16/9, 2020 at 0:20 Comment(2)
Why not just do DESCRIPTION="${variable1}\n${variable2}\n" ? Seems like a cleaner way to achieve the same thing, unless I'm missing something.Berwickupontweed
there is a difference, ive just tested it. with that method i need -e if im to echo it, with what i suggested you don't. so theirs deffo a difference!Earthly
A
1
#!/bin/bash

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

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

echo $concatString 
echo $concatString2
Arleyne answered 25/12, 2016 at 17:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.