In PHP, strings are concatenated together as follows:
$foo = \"Hello\";
$foo .= \" World\";
Here, $foo
becomes \"Hello World\"
I wanted to build a string from a list. Couldn't find an answer for that so I post it here. Here is what I did:
list=(1 2 3 4 5)
string=''
for elm in "${list[@]}"; do
string="${string} ${elm}"
done
echo ${string}
and then I get the following output:
1 2 3 4 5
bla=hello
laber=kthx
echo "${bla}ohai${laber}bye"
Will output
helloohaikthxbye
This is useful when
$blaohai
leads to a variable not found error. Or if you have spaces or other special characters in your strings. "${foo}"
properly escapes anything you put into it.
$ a=hip
$ b=hop
$ ab=$a$b
$ echo $ab
hiphop
$ echo $a$b
hiphop
Even if the += operator is now permitted, it has been introduced in Bash 3.1 in 2004.
Any script using this operator on older Bash versions will fail with a "command not found" error if you are lucky, or a "syntax error near unexpected token".
For those who cares about backward compatibility, stick with the older standard Bash concatenation methods, like those mentioned in the chosen answer:
foo="Hello"
foo="$foo World"
echo $foo
> Hello World
In my opinion, the simplest way to concatenate two strings is to write a function that does it for you, then use that function.
function concat ()
{
prefix=$1
suffix=$2
echo "${prefix}${suffix}"
}
foo="Super"
bar="man"
concat $foo $bar # Superman
alien=$(concat $foo $bar)
echo $alien # Superman
Here is a concise summary of what most answers are talking about.
Let's say we have two variables and $1 is set to 'one':
set one two
a=hello
b=world
The table below explains the different contexts where we can combine the values of a
and b
to create a new variable, c
.
Context | Expression | Result (value of c)
--------------------------------------+-----------------------+---------------------
Two variables | c=$a$b | helloworld
A variable and a literal | c=${a}_world | hello_world
A variable and a literal | c=$1world | oneworld
A variable and a literal | c=$a/world | hello/world
A variable, a literal, with a space | c=${a}" world" | hello world
A more complex expression | c="${a}_one|${b}_2" | hello_one|world_2
Using += operator (Bash 3.1 or later) | c=$a; c+=$b | helloworld
Append literal with += | c=$a; c+=" world" | hello world
A few notes:
+=
is better from a performance standpoint if a big string is being constructed in small increments, especially in a loop{}
around variable names to disambiguate their expansion (as in row 2 in the table above). As seen on rows 3 and 4, there is no need for {}
unless a variable is being concatenated with a string that starts with a character that is a valid first character in shell variable name, that is alphabet or underscore.See also: