Concatenation is one of the most popular and used string operations. String concatenation is just a decorative programming word for joining strings collectively by adding one string to another string’s end.

In this article, we will show how to concatenate strings in bash.

Concatenating Strings

The easiest way to concatenate two or more string variables is to write them one after another:

VAR1= "Hi,"
VAR2=" Lucky"
VAR3="$VAR1 $VAR2"
echo "$VAR3."

The last line will echo the concatenated string:

Output:
Hi, Lucky

With the help of a literal string, you can concatenate one or more variable:

VAR1= "Hey,"
VAR2= "${VAR1}World."
echo "$VAR2."
Output:
Hello, World

The example over variable VAR1 is enveloped in curly braces to guard the variable name against surrounding characters. When another valid variable-name character reflects the variable, you must have it in curly braces ${VAR1}.

To circumvent any word splitting or globbing issues, you should regularly try to use double quotes nearby the variable name if you want to suppress variable addition and special treatment of the backslash character rather than dual-use single quotes.

Bash does not separate variables by “type”; variables are used as integer or string depending on contexts. You can also combine variables that contain only digits.

VAR1 = "Hey, "
VAR2 = 2
VAR3 = " Lucky"
VAR4 = "$VAR1$VAR2$VAR3"
echo "$VAR4"
Output:
Hey, 2 Lucky

Concatenating Strings with the += operator

The other way of concatenating strings in bash is by combining variables or literal strings to a variable using the += Operator:

VAR1="Hey, "
VAR1+=" Lucky"
echo "$VAR1."
Output:
Hey, Lucky

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

languages. sh
VAR= ""
for ELEMENT in 'Oxygen' 'Helium' 'Lime' 'Belly'; do
VAR+="${ELEMENT} "
done
echo "$VAR."
Output:
Oxygen Helium Lime Belly

Conclusion
Concatenating string variables is one of the most significant operations in Bash scripting. After reading this article, you should have a good knowledge of how to concatenate strings in bash. If you have any queries related to bash connect with us now.

Leave a Reply

Your email address will not be published. Required fields are marked *