Simple guide to concatenate strings in bash with examples

How to concatenate strings with underscore, newline, whitespace or any other character in bash? How to append substrings in a string in bash or shell script? How to append starings in a variable using for loop with whitespace? Bash join strings with separator.

These are some of the common questions which we will address in this tutorial. concatenate means nothing but linking or putting things together in some sort of chain or series. You may choose to put two or multiple strings together by any separation character.

 

Basic concatenation of two strings with no separator

This is quite a straight forward use case wherein we have two variables with some string and you want to concatenate them

For example, I have two variables:

Simple guide to concatenate strings in bash with examples

As you have noticed VAR1 already contains an extra space so we are just printing both variables together, the output from this script would be:

]# ./eg_1.sh
Hello World

Now we can also join VAR1 and VAR2 into a third variable VAR3 and the output would be the same i.e. "Hello World"

Simple guide to concatenate strings in bash with examples

 

Join strings with special character as separator

Now the above was a very basic example, let' take it to the next level. In this example we will concatenate strings with underscore, you may choose any other separator such as comma, whitespace, hyphen etc.

Using above script as an example, what would happen if I just place "_" (underscore) between both the variables, it should work right?

Simple guide to concatenate strings in bash with examples

Let's check the output from this script:

~]# ./eg_1.sh
World

From our output "Hello" is missing, WHY?

Because bash considered $VAR_ as one variable and $VAR2 as second. Since $VAR_ doesn't exist so Hello is missing. So in such case always use curly braces to denote a variable when working with concatenation.

Simple guide to concatenate strings in bash with examples

 

So as you see now I have used curly braces {} to make sure the separator is not considered part of the variable, now let's check the output from the script:

~]# ./eg_1.sh
Hello_World

This is the one of the most important thing you should always remember when working with bash string concatenation. Now you can use any other special character here to combine both the strings.

 

Concatenate in a loop (append strings to a variable)

Now assuming you have a requirement where in you have to test network connectivity of multiple hosts and then print a summary with list of success and failed hosts. This would require you to keep storing the list of success and failed hosts, this can be done using various methods but we will use += operator to store the list of strings in a variable (or convert to array based on your requirement)

 

In this example script I have defined a list of 4 hosts out of which 2 are reachable (yeah I know this already) while two are un-reachable but we will use a script to check this. Based on the ping output we will append the string in different variable

Simple guide to concatenate strings in bash with examples

 

Output from this script:

~]# ./eg_1.sh
Reachable: 192.168.43.154 192.168.43.10
Not Reachable: 192.168.43.100 192.168.43.120

 

Here if you notice this if condition is the main part which stores the server list. I have intentionally added an empty whitespace after $server so that there is a gap between list of servers when added to SUCCESS or FAILED

    if [[ $? -eq 0 ]];then
       # If success then append the output in SUCCESS variable
       SUCCESS+="$server "
    else
       # If failed then append the server in FAILED variable
       FAILED+="$server "
    fi

You may choose to strip the last whitespace character at the end of execution of that creates a problem in your output:

# Strip last whitespace char
SUCCESS=`echo $SUCCESS | sed 's/ $//g'`
FAILED=`echo $FAILED | sed 's/ $//g'`

 

Concatenate strings using new line character

You can use the same operator += to append strings with new line character, although printing the output would require certain extra handling. In this example I have created an array with some values, I will iterate over these values and then join them together with a new line character at the end

Simple guide to concatenate strings in bash with examples

 

Output from this script:

~]# ./eg_1.sh
OUTPUT: ab
cd
ef
gh
ij

 

So I have combined all the strings in a for loop (you can also use while or any other loop - doesn't matter) using new line character. By default echo will not be able to understand "\n" and will consider it as a text so we use -e to enable interpretation of backslash escapes. The -n is used with echo to suppress the last line or you will have an extra new line in the end, you can also use printf to avoid all this additional argument.

 

Conclusion

In this tutorial we learned about bash string concatenation using different joining character such as whitespace, newline, special characters etc. You can use += operator in all sorts of scenarios to combine strings. But one thing to remember is that by default in a loop += will append the string in the end of variable, if you have a different requirement than that would need special handling.

Leave a Comment

Please use shortcodes <pre class=comments>your code</pre> for syntax highlighting when adding code.