I need to concatenate two strings in bash, so that:
string1=hello
string2=world
mystring=string1+string2
echo mystring
should produce
helloworld
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"
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
${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.
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)
.
join
could also do the thing for you.