Enter your email address below and subscribe to our newsletter

How to Concatenate String Variables in Bash

Learn how to concatenate string variables using 3 simple methods in bash.

Share your love

There can be multiple reasons why would want to concatenate string variables in bash such as you’d want to build file paths, construct a long string of commands, or manipulate user input.

So in this tutorial, I will walk you through ways you can concatenate string variables in bash:

  • Using the += operator
  • Using the string concatenation method
  • Using string variable concatenation in a bash loop

Let’s start with the first one.

1. Using the += operator

The idea here is you first have a string variable assigned with some values. Now, to concatenate more variables to the existing variable, you use the += operator.

But you don’t require any additional variables. You use the same variable to concatenate string variables but append the += operator at the variable indicating you want to add more data to the existing variable:

#!/bin/bash

message="Hello" #First varible with values 
message+=" world" #String concatination to existing variable 
message+=", from Bash!" #Another concatination
echo "Final value of message: $message"

If you execute the above script, it will give you the following output:

Use the += operator to concatinate bash string variables

In simple terms, you use the same variable with the += to store the contamination value multiple times and then print the value to concatenate multiple string variables in bash.

2. Using the string concatenation

This is the most popular way of concatenating string variables in bash, and there’s a reason why. This is quite simple compared to the first, where you use multiple variables to store strings and then use a new variable to concatenate all the values.

To use the string concatenation, refer to the following command syntax:

#!/bin/bash

Variable1="String1"
Variable2="String2"
Output_variable="$Variable1$Variable2"
echo "$Output_variable"

Looks complex? Let me share a simple example:

#!/bin/bash

greeting="Hello" #First string variable
name="Alice" #Second string variable
message="$greeting$name" #Concatenating both strings in new variable
echo "$message" #Priting concatenated string

Now, let’s break it down. Here,

  • greeting="Hello": This line initializes a string variable greeting with the value "Hello".
  • name="Alice": This line initializes another string variable name with the value "Alice".
  • message="$greeting$name": This line concatenates the values of greeting and name variables and assigns the combined string to the message variable.
  • echo "$message": This line prints the value of the message variable, which is "HelloAlice".

When executed, it will show the following output:

Concatenate bash string variables using the string concatenation method

3. Using loops to concatenate strings

While the above two methods will surely get the work done, only when you’re just getting started. The real implementation of Linux starts with scripting and if you have to concatenate strings at a large scale, then, you can refer to this method.

First, let me share a simple script utilizing arrays with while loop in Linux:

# Initialize an empty string
result=""

# Array of strings to concatenate
names=("Kabir" "Rahim" "Tulsidas" "Premchand")

# Initialize the index
index=0

# Loop through the array and concatenate each string with a comma and space
while [ "$index" -lt "${#names[@]}" ]; do
 result+="${names[$index]}, "
 ((index++))
done

# Remove the trailing comma and space
result="${result%, }"

echo "Concatenated names: $result"

Here,

  • result="": This line declares a variable named result and initializes it with an empty string. This variable will be used to store the concatenated names.
  • names=("Kabir" "Rahim" "Tulsidas" "Premchand"): This line declares an array named names and initializes it with four string elements: "Kabir", "Rahim", "Tulsidas", and "Premchand". These are the names that we want to concatenate.
  • index=0: This line declares a variable named index and initializes it with the value 0. This variable will be used as a counter to keep track of the current position in the names array during the loop.
  • while [ "$index" -lt "${#names[@]}" ]; do: This is the loop condition. It checks if the value of index is less than the length of the names array. The loop will continue to execute as long as this condition is true.
    • result+="${names[$index]}, ": Inside the loop, this line concatenates the current name (${names[$index]}) with a comma and a space (, ) to the result variable using the += operator.
    • ((index++)): This line increments the value of index by 1 for the next iteration of the loop.
  • done: This keyword marks the end of the while loop.
  • result="${result%, }": After the loop finishes, this line removes the trailing comma and space from the result string using parameter expansion. The %, pattern matches the last occurrence of ", " in the string, and the substitution removes it.
  • echo "Concatenated names: $result": Finally, this line prints the concatenated names stored in the result variable, preceded by the string "Concatenated names: ".

In simple terms, the while loop will iterate over the names array, concatenating each element to the result variable with a comma and space.

When executed, it will give you the following output:

Concatenate bash string variables using the while loop

Wrapping up…

In this tutorial, I went through 3 ways of how you can concatenate string variables in bash. If you are a beginner, I would suggest going with the 2nd method will get the job done.

But if you are an advanced user, then will be able to get the most out of it.

Share your love
Kabir
Kabir

A tech journalist whose life revolves around networks.

Newsletter Updates

Enter your email address below and subscribe to our newsletter

Stay informed and not overwhelmed, subscribe now!