43

I need to concatenate two strings in bash, so that:

string1=hello
string2=world

mystring=string1+string2

echo mystring should produce

helloworld

1

4 Answers 4

57

You don't need to use {} unless you're going to use bash variable parameters or immediate append a character that would be valid as part of the identifier. You also don't need to use double quotes unless you parameters will include special characters.

x=foo
y=bar
z=$x$y        # $z is now "foobar"
z="$x$y"      # $z is still "foobar"
z="$xand$y"   # does not work
z="${x}and$y" # does work, "fooandbar"
z="$x and $y" # does work, "foo and bar"
1
  • 2
    This is what I was looking for [z="$xand$y" # does not work ..... z="${x}and$y" # does work, "fooandbar"]. Thanks.
    – blokeish
    May 19, 2017 at 7:20
43

simply concatenate the variables:

mystring="$string1$string2"
19

In case you need to concatenate variables with literal strings:

string1=hello
string2=world
mystring="some ${string1} arbitrary ${string2} text"

echo $mystring will produce:

some hello arbitrary world text

1
  • 6
    You can use the ${var} format any time you like, but you only need it when $var is to be immediately followed by another valid variable-name character... eg: $vararbitary will interpret a variable named "vararbitary", but you can get around it by using ${var}arbitary .... oops, I just saw khamer's abswer.. but I may as well leave the comment here.
    – Peter.O
    Mar 29, 2011 at 15:32
12

If you want to concatenate a lot of variables you can also use += to append strings.. This may increase readability..

mystring=${string1}
mystring+=${string2}
mystring+=${string3}
mystring+=${string4}
echo ${mystring}

As mentioned by other answers the {} are not needed here but I personally always use them to avoid some syntax errors.

+= can also be used to append values to arrays: array+=($b).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.