Quantcast
Channel: Linux Guides, Tips and Tutorials | LinuxScrew
Viewing all articles
Browse latest Browse all 314

Concatenate Strings in Bash/Shell Scripts, With Examples

$
0
0

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.

View the original article from LinuxScrew here: Concatenate Strings in Bash/Shell Scripts, With Examples


Viewing all articles
Browse latest Browse all 314

Trending Articles