Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to concatenate string variables in Bash

In PHP, strings are concatenated together as follows:

$foo = "Hello"; $foo .= " World"; 

Here, $foo becomes "Hello World".

How is this accomplished in Bash?

like image 870
Strawberry Avatar asked Nov 15 '10 05:11

Strawberry


People also ask

How do I concatenate a variable to a string in bash?

The += Operator in Bash Bash is a widely used shell in Linux, and it supports the '+=' operator to concatenate two variables. As the example above shows, in Bash, we can easily use the += operator to concatenate string variables.

How do you combine variables and strings?

In JavaScript, we can assign strings to a variable and use concatenation to combine the variable to another string. To concatenate a string, you add a plus sign+ between the strings or string variables you want to connect. let myPet = 'seahorse'; console.


2 Answers

foo="Hello" foo="${foo} World" echo "${foo}" > Hello World 

In general to concatenate two variables you can just write them one after another:

a='Hello' b='World' c="${a} ${b}" echo "${c}" > Hello World 
like image 107
codaddict Avatar answered Oct 03 '22 11:10

codaddict


Bash also supports a += operator as shown in this code:

A="X Y" A+=" Z" echo "$A" 

output

X Y Z

like image 32
thkala Avatar answered Oct 03 '22 09:10

thkala