Bash Concatenate Strings
Quick Reference
[#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:
Concatenating a variable and a string:
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:
Concatenating multiple numbers:
[#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.