Bash Concatenate Strings

Last Updated 2022-10-18

Quick Reference

 $ X="String"
 $ X+="Concatenation" 
 $ echo $X
 # Output

[#what-is-concatenation]What is Concatenation?[#what-is-concatenation]

Concatenation is the process of joining two strings together into one result. Some common use cases include creating a string containing multiple variables, and formatting messages containing user-defined inputs.

[#basic-concatenation]Basic Concatenation[#basic-concatenation]

In Bash, when variables or strings are written one after another, they automatically concatenate. In the following examples, the code will echo the same output to the terminal.

Concatenating variables:

 $ X="String"
 $ Y="Concatenation!"
 $ echo "${X}${Y}"
 # Output

Concatenating a variable and a string:

 $ X="String"
 $ echo "${X}Concatenation!"
 # Output

The curly braces are used to “protect” the names of the X and Y variables from other characters in the string. They make it clear to Bash that you are using a variable with a specific name. Use double quotes for strings containing variable names - this tells Bash to interpolate, or substitute in, the values of the variables.

[#mult-variable-types]Concatenation with multiple variable types[#mult-variable-types]

Bash infers the type of variables depending on how they are used. So, this means we can use integer or boolean variables in string concatenation as well.

Concatenating an integer and a string:

 $ X="The number four: "
 $ Y=4
 $ echo "$X$Y"
 # Output
 The number four: 4

Concatenating multiple numbers:

 $ X=314
 $ Y=159
 $ echo "$X$Y"
 # Output

[#using-addition-assignment-operator]Concatenation with += operator[#using-addition-assignment-operator]

You can use the += operator to append to the end of a string variable.

 $ X="Pi is the number "
 $ X+=3.14159
 $ X+= " and it is very handy."
 $ echo "$X"
 # Output
 Pi is the number 3.14159 and it is very handy.