Concatenate Strings in Bash/Shell Scripts, With Examples

Bash Concatenate Strings

Here’s a short article on concatenating (merging) strings in Bash – the right way. Examples included.

There are various ways two or more strings could be joined in a shell script. Various programs will accept strings and return them merged/concatenated – but using the side-effect of a programs operation to concatenate strings is a bit of a waste of time, so this article will focus on the simplest, most readable method.

Inserting a String into Another

A string can be inserted when creating another string as follows:

#!/bin/bash
string1="Hello"
string2="${string1} there!"
echo "${string2}"

What is the ‘#!’ in Linux Shell Scripts?

As many strings as required can be included – it’s not limited to two!

In the echo command above, string2 is not echoed directly but is also wrapped in double-quotes – here’s why.

The names of the variables are wrapped in curly braces ({}) – this is to separate the variable name from any surrounding characters so that they are not confused.

Merging/Concatenating Strings in Bash Scripts

Two existing strings can be merged when creating a new string:

#!/bin/bash
string1='Hello'
string2='there!'
string3="${string1} ${string2}"
echo "${string3}"

Appending

The += operator can be used to append one string to another:

string1="Hello, "
string1+=" there!"
echo "${string1}"

This is a neat shortcut that doesn’t require creating additional variables.

SHARE:
nv-author-image

Brad Morton

I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Reply

Your email address will not be published. Required fields are marked *