How to Concatenate Strings in Bash

Suraj Joshi Feb 02, 2024
  1. String Concatenation Placing One String Variable After Another
  2. String Concatenation Using the += Operator
How to Concatenate Strings in Bash

String concatenation is one of the most widely used operations in the programming, which refers to joining two or more strings by placing one at the end of another. To concatenate strings in Bash, we can write the string variables one after another or concatenate them using the += operator.

String Concatenation Placing One String Variable After Another

We can concatenate string by placing string variables successively one after another.

STR1="Delft"
STR2="Stack"

STR3="$STR1$STR2"

echo "$STR3"

Output:

DelftStack

In the above example, we concatenate STR1 and STR3 and assign the concatenated string to STR3. The double-quotes " " are used to prevent splitting or globbing issues.

We use the echo command to print the output.

Concatenate One or More Variables With Literal Strings

STR1="Delft"

STR3="${STR1}-Stack"

echo "$STR3"

Output:

Delft-Stack

Here, {} is used to isolate the string variable from string literal.

It concatenates string variable STR1 with string literal -Stack.

Concatenate More Than Two Strings Together

We can place the string variables and literals successively to concatenate more than two string variables together.

STR1="Delft"
STR2="-Stack"
STR3="Check them out!!"

STR4="${STR1}${STR2} has great programming articles.${STR3}"

echo "$STR4"

Output:

Delft-Stack has great programming articles.Check them out!!

Concatenate Numeric and String Literals

The variables are not differentiated by Bash based on the type while concatenating. They are interpreted as integer or string depending upon the context.

STR1="FIVE-"
STR2=5

STR4="$STR1$STR2"

echo "$STR4"

Output:

FIVE-5

It concatenates string variable FIVE- and 5 together.

String Concatenation Using the += Operator

Bash also allows string concatenation using the += operator. Simply a+=b can be understood as a=a+b.

STR1="Delft"
STR2="-Stack"

STR1+=$STR2

echo "$STR1"

Output:

Delft-Stack

Here, STR2 is appended at the end of STR1, and the result is stored in the STR1 variable.

To append multiple values, we can use a simple for loop.

NUMS=""
for NUM in 'One' 'Two' 'Three' 'Four'; do
  NUMS+="${NUM} "
done

echo "$NUMS"

Output:

One Two Three Four 
Author: Suraj Joshi
Suraj Joshi avatar Suraj Joshi avatar

Suraj Joshi is a backend software engineer at Matrice.ai.

LinkedIn

Related Article - Bash String