Bash Concatenate String Variables

Updated on

2 min read

Bash Concatenate Strings

One of the most commonly used string operations is concatenation. String concatenation is just a fancy programming word for joining strings together by appending one string to the end of another string.

In this article, we will explain how to concatenate strings in Bash.

Concatenating Strings

The easiest way to concatenate multiple string variables is by simply placing them next to one another:

VAR1="Hello,"
VAR2=" World"
VAR3="$VAR1$VAR2"
echo "$VAR3"

The last line will echo the concatenated string:

Hello, World

You can also concatenate one or more variables with literal strings:

VAR1="Hello, "
VAR2="${VAR1}World"
echo "$VAR2"
Hello, World

In the example above, variable VAR1 is enclosed in curly braces to protect the variable name from surrounding characters. When another valid variable-name character follows the variable, you must enclose it in curly braces ${VAR1}.

Always use double quotes around the variable name to avoid issues with word splitting or globbing. If you want to suppress variable interpolation and special treatment of the backslash character instead of double use single quotes.

Bash does not segregate variables by “type”; variables are treated as integers or strings depending on contexts. You can also concatenate variables that contain only digits.

VAR1="Hello, "
VAR2=2
VAR3=" Worlds"
VAR4="$VAR1$VAR2$VAR3"
echo "$VAR4"
Hello, 2 Worlds

Concatenating Strings with the += Operator

Another way of concatenating strings in Bash is by appending variables or literal strings to a variable using the += operator:

VAR1="Hello, "
VAR1+=" World"
echo "$VAR1"
Hello, World

The following example is using the += operator to concatenate strings in bash for loop :

languages.sh
VAR=""
for ELEMENT in 'Hydrogen' 'Helium' 'Lithium' 'Beryllium'; do
  VAR+="${ELEMENT} "
done

echo "$VAR"
Hydrogen Helium Lithium Beryllium

Conclusion

Concatenating string variables is one of the most fundamental operations in Bash scripting. After reading this tutorial, you should have a good understanding of how to concatenate strings in Bash. You can also check out our guide for comparing strings .

If you have any questions or feedback, feel free to leave a comment.