1. Overview

In this quick tutorial, we’ll explore how to concatenate string variables in a shell script.

2. The += Operator in Bash

Bash is a widely used shell in Linux, and it supports the ‘+=‘ operator to concatenate two variables.

An example may explain this operator quickly:

$ myVar="Hello"
$ myVar+=" World" 
$ echo $myVar
Hello World

As the example above shows, in Bash, we can easily use the += operator to concatenate string variables.

Bash’s += works pretty similar to compound operators in other programming languages, such as Java. However, we should note that Bash’s += operator behaves differently when we work with numbers.

Again, let’s understand it with an example:

$ myNum=100
$ myNum+=200

This time, we first assigned the value 100 to the variable myNum. Then, we used the += operator to “add” another value of 200 to the variable. So, we may expect that the myNum variable has a value of 300 now.

But, if we check the value of the myNum variable, the result may surprise us:

$ echo $myNum 

As we can see in the output above, Bash treats the values as strings. If we want to calculate the sum of the two integer numbers and assign the result to the variable myNum, we can use the += operator together with Bash’s arithmetic expansion:

$ myNum=100
$ ((myNum+=200))
$ echo $myNum 

Bash’s += operator is handy for concatenating a string variable and applying the assignment in one shot. However, if we want to join multiple variables, it won’t be the best choice. Moreover, if our shell is not Bash, our shell may not support the += operator.

So, next, let’s see a more general solution of string concatenation in a shell script.

3. Concatenating String Variables in POSIX Shell

In shell programming, we can use parameter expansion to concatenate variables.

Let’s see an example:

$ var1=hello
$ var2=and
$ var3=bye
$ var4="${var1} ${var2} ${var3}"
$ echo $var4
hello and bye

As we’ve seen in the example above, we’ve concatenated three variables’ values using parameter expansion.

4. Conclusion

In this quick article, we’ve addressed using Bash’s += operator to concatenate variables.

Further, if we need to concatenate multiple variables or our shell is not Bash, we can use the shell’s parameter expansion to do the job.

Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.