Skip to content

How to concatenate strings in Bash?

  • by
  • 2 min read

String concatenation is a rather popular string operation in just about any programming language. When writing scripts with Bash, you might need to concatenate strings at times as well. 

Now there are four ways you could concatenate strings in Bash as follows.

We’ll be going over all four of the methods in this article.

Also read: How to exit Bash script?


Writing string variables after each other

One of the simplest ways of concatenating a string is to write the string variables after each other. Take a look at the following example.

str1 = "Candid."
str2 = "Technology"
str3 = "$str1$str2" 
echo "$str3"

The output of the above snippet would be the concatenated strings, that is, Candid.Technology.

Also read: Bash While loop explained


Writing a string variable with a literal string

Another common method of concatenating strings is to write a string variable enclosed in curly brackets and a string in one variable declaration. 

str1 = "Candid."
str2 = "${str1}Technology"
echo "$str2"

The above snippet will combine the str1 string variable with the literal string provided and will echo Candid.Technology.

Also read: Bash functions explained


Using the shorthand operator

The shorthand operator, +=, is also used to concatenate strings in Bash. You don’t even need a second variable when using the shorthand operator. It works just like it would with numerical values.

str1 = "Candid."
str1 +="Technology"
echo "$str1"

The above snippet will combine the two strings and output Candid.Technology.

Also read: How to create Bash aliases?


By adding a character in between strings

Like you can concatenate strings by writing them one after another, you can also combine them by adding a character in between and declaring everything in one variable. This works great where you need to separate as usual. 

str1 = "Candid"
str2 = "Technology"
str3 = "$str1.$str2"
echo "$str3"

The above snippet will combine the two string variables with the period in between and output Candid.Technology. 

Also read: How to check if a file or directory exists in Bash?

Yadullah Abidi

Yadullah Abidi

Yadullah is a Computer Science graduate who writes/edits/shoots/codes all things cybersecurity, gaming, and tech hardware. When he's not, he streams himself racing virtual cars. He's been writing and reporting on tech and cybersecurity with websites like Candid.Technology and MakeUseOf since 2018. You can contact him here: yadullahabidi@pm.me.

>