Skip to content

How to concatenate strings in Bash?

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?

Hello There!

If you like what you read, please support our publication by sharing it with your friends, family and colleagues. We're an ad-supported publication. So, if you're running an Adblocker, we humbly request you to whitelist us.

Share on facebook
Share on whatsapp
Share on twitter
Share on reddit
Share on linkedin
Share on pocket
Share on pinterest
Share on telegram
Share on stumbleupon
Share on digg
Share on tumblr
Share on email
Share on skype
Share on xing
Share on vk
Share on odnoklassniki
Share on mix