Mastering Bash Concatenate Strings in Linux: [10 Best Examples]

Mastering Bash Concatenate Strings in Linux: [10 Best Examples]

In this tutorial, we will learn about mastering bash concatenate strings in Linux using 10 best examples. In bash scripting, string concatenation is one of the useful and important operation which is implemented in many use cases. For example, suppose you have written a bash script which expect multiple inputs from user during runtime. When your script read these input, it must store and concatenate these in some manner for further processing. We will talk about in-depth usage of string concatenation and various methods to achieve it in bash scripting. Let us begin the tutorial.

 

Why String Concatenation is Required?

As discussed, string concatenation in bash scripting is one of the most important use case. There are many ways which can be used to concatenate two or more strings of same data type as well as different data types. For example, using += operator, using special character, using echo function and so on. We will look at each of these string concatenation methods in the next section.

How to Concatenate Strings Without Using Operators? 

For a beginner in bash scripting, there must be a thought at some point that can we concatenate strings in a simple and straight forward way, without using any special methods? . The answer is yes, we can do that. In the below example, we have created a simple bash script. It declares three variables, country, state and city. We have assigned the values to each of these variables.

Now, we want to concatenate these three string. So, we have declared another variable called output in which we have stored the concatenated string output. We have used ""  notation inside which we have called all three variables using $ symbol. This way we can achieve string concatenation without using any specific methods. Save and execute below script. You will get the similar output as shown below.

Also Read: [ MariaDB ] How to Reset root User Password

Example-1: Join Strings without using Any Method

#!/bin/bash

country="India"
state="Rajasthan"
city="Jaipur"

output="$country $state $city"
echo "$output"

OUTPUT

India Rajasthan Jaipur

 

Mastering Bash Concatenate Strings in Linux: [10 Best Examples]

So far we learnt about concatenating string in a pretty straight forward manner. But this will not be suitable in all type of use cases. Let us now look at different methods to achieve the same goal . In the upcoming sections, we will cover the methods to concatenate strings like using assignment operator, using echo function, using special characters and using for loop.

 

Using Assignment (`+=`) Operator

In this method, We declare a variable and store some value to it. Next, we add strings to this variable using += operator. Let us implement this concept using below example. We have declared variable “greet” and store the value of type string to it “Hello”. Next we have added another string at the end of this variable called “LinuxNasa”. Next, when we print the variable “greet”, it will return the output “Hello LinuxNasa”.

Example-2: Join Strings of Same Data Type

#!/bin/bash

greet="Hello "

greet+="LinuxNasa"
echo "$greet"

OUTPUT

Hello LinuxNasa

 

Example-3: Join Strings and Numbers

It is also possible to concatenate numbers with strings. In the below example, we have declared two variable, “greet” store the value “Hello” and “id” store the value “6512”. We have concatenated both the variable using += operator as shown below.

#!/bin/bash

greet="Hello "
id=6512

greet+="LinuxNasa, Your id is: $id"
echo "$greet"

OUTPUT

Hello LinuxNasa, Your id is: 6512

 

Example-4: Join Strings with an Array

In some of the use cases, we may want to add additional elements to an array. In the below example, we have declared an array called “TECHNOLOGY” which stores couple of technologies. Next, we added two more technologies to this array using += operator as shown below.

#!/bin/bash

declare -a TECHNOLOGY='Python MySQL OpenShift Kubernetes'

TECHNOLOGY+=' Golang Kibana'
echo "$TECHNOLOGY"

OUTPUT

Python MySQL OpenShift Kubernetes Golang Kibana

 

Using echo Function 

Another way to use is by adding the strings and printing is on console using echo function. In the below example, we have declared two variables. First variable “LANGUAGE stored couple of language. Second variable “MORE_LANGUAGE” stores two language. we have added all these strings together and printed the output using echo function on the console.

Also Read: How to Update or Upgrade Packages on Ubuntu/Debian

Example:5 –  Join Strings using echo Function

#!/bin/bash

LANGUAGE="English French German Science"
MORE_LANGUAGE="Maths History"

echo "Languages Known: $LANGUAGE"
echo "Additonal languages added: $LANGUAGE $MORE_LANGUAGE"

OUTPUT

Languages Known: English French German Science
Additonal languages added: English French German Science Maths History

 

Using any Special Character

This is very interesting and usable method to concatenate strings. In this method, we add two or more strings using some special characters say, -, &, # or any other character. In the below example, We have concatenated two variables namely, country and state using : character. We have printed the output on console using echo function.

Example-6: Join Strings using :  Special Character

#!/bin/bash

country="India"
state="Rajasthan"

output=$country:$state
echo "$output"

OUTPUT

India:Rajasthan

 

Example-7: Join Strings using _ Special Character

Let us again execute above script by replacing the special character : to _ and see what happens.

#!/bin/bash

country="India"
state="Rajasthan"

output="$country_$state"
echo "$output"

OUTPUT

Rajasthan

As you notice, it only printed the state. This is because bash interpreted  $country_ as first variable and $state as second variable. Since there is no such variable called $country_ so it only recognized second variable and printed the output. To overcome this error, we always wrap our variables in curly braces. So the modify above code and executed again as shown below

 

Example-8: Modified Code

To fix the above code, we will wrap both the variable inside {} braces. It will now return the correct output as shown below.

#!/bin/bash

country="India"
state="Rajasthan"

output="${country}_${state}"
echo "$output"

OUTPUT

India_Rajasthan

 

Using for Loop

Another interesting method for concatenating strings is by using for loop. Suppose, you have a requirement where you want to segregate some elements based on a conditions and store each element in a variable based on if it satisfy the condition or now. How will you achieve that? . We can utilize for loop method.

In the below example, we have declared an array which stores couple of “IP” addresses. Our job is to check which IPs in the array are reachable. If it is active, store it in variable “SUCCESS” . If the IP is not reachable, store it in the variable “FAILED”. Print both the variable using echo function.

Example-9: Join Strings using for Loop

#!/bin/bash

# Define empty variables
SUCCESS=""
FAILED=""

# Declare an array as we have to iterate over individual value
declare -a HOSTS='132.10.20.8 132.10.20.9 132.10.20.10 132.10.20.11 132.10.20.12'

# use for loop to interate over HOSTs array
for ip in ${HOSTS[@]}; do
# ping with 2 packages and check for connectivity
ping -c 2 -q $ip >/dev/null 2>&1
if [[ $? -eq 0 ]]; then
# If reachable then append output to SUCCESS variable
SUCCESS+="$ip "
else
# if not reachable then append to FAILED variable
FAILED+="$ip "
fi
done

#print status of all IPs
echo "Active IP: $SUCCESS"
echo "INACTIVE IP: $FAILED"

OUTPUT

Active IP: 132.10.20.11 132.10.20.12
INACTIVE IP: 132.10.20.8 132.10.20.9 132.10.20.10

 

Example-10: Join Strings using for Loop and Special Character

Another use case where for loop can be used for concatenation strings is while reading space separated input. This input may be provided by user at runtime or stored in a variable within the script. Once we read the input, we can use for loop to separate each of the string in the variable using some character or special character. We have added : between each string in the variable.

#!/bin/bash

languages="English French German Science"
IFS=' ' read -ra words <<< "$languages"

for ((i=0; i<${#words[@]}; i++)); do
echo -n "${words[i]}"
if [ $i -lt $((${#words[@]} - 1)) ]; then
echo -n ":"
fi
done
echo

OUTPUT

English:French:German:Science

 

Summary

We have covered most of the methods for concatenating strings in bash script. If you gain the hands on on these basic methods, it will become easy to write the bash script and implement different use cases. I have also written some interesting articles on MariaDB. You can start on these articles but first have a look at How to Install MariaDB in Linux [5 Easy Steps].

 

Leave a Comment