Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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

string1=hello
string2=world

mystring=string1+string2

echo mystring should produce

helloworld

share|improve this question

4 Answers 4

up vote 11 down vote accepted

simply concatenate the variables:

mystring="$string1$string2"
share|improve this answer

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

share|improve this answer
3  
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 '11 at 15:32

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"
share|improve this answer

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).

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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