Site icon DesignLinux

Bash Concatenate Strings

Bash Concatenate Strings

In any programming language the concatenation is the commonly used string operations. String concatenate is used to joining the two or more strings together by appending one to end of another string. In this tutorial, you will learn how to concatenate strings in Bash.

Concatenating Strings

It’s very easy to concatenate multiple string variables by writing them one after another:

VAR1="Hey,"
VAR2=" Dude!"
VAR3="$VAR1$VAR2"
echo "$VAR3"

In the last line the echo will print the concatenated string:

Hey, Dude!

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

VAR1="Hey, "
VAR2="${VAR1}Dude"
echo "$VAR2"
Hey, Dude!

Here, in above example VAR1 variable is protected from surrounding characters by enclosing with curly braces. You must enclose the variable in curly braces ${VAR1} when it is followed by another valid variable-name.

It is best practice to use the double quotes around the variable name to avoid any word splitting issues. When you need to use backslash characters use the single quotes instead of double quotes.

Bash does not segregate variables by “type”, variables are treat as integer or string depending on contexts. You can also concatenate variables that contain only digits.

VAR1="Hey, "
VAR2=5
VAR3=" Dude"
VAR4="$VAR1$VAR2$VAR3"
echo "$VAR4"
Hey, 5 Dude

Concatenate Strings with the += Operator

You also can concatenate the strings in bash using the += operator by appending variables or literal strings to a variable.

VAR1="Hey, "
VAR1+=" Dude"
echo "$VAR1"
Hey, Dude

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

Below is the given an example to concatenate strings in bash for loop:

VAR=""
for STATE in 'Florida' 'California' 'Texas' 'Alaska'; do
  VAR+="${STATE} "
done

echo "$VAR"
Florida California Texas Alaska

Conclusion

You learned how to concatenate the string variables in bash scripting. You can also check our guide about comparing strings.

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

Exit mobile version