String Concatenation in Bash [6 Methods]

Concatenation means to join two or more elements altogether. When two strings are concatenated in a bash string, it generally refers to appending the new string to the right of the existing string. Let’s see some of the methods of bash string concatenation strings.

What Is Concatenation in Bash?

Concatenation is merging two or more strings into a new string. Building new string, file_path, and manipulating string are the common uses of string concatenation. Concatenation is important for formatting the output of a string and for flexibility in making dynamic strings.

6 Methods to Concatenate Strings in Bash

In bash scripting, string concatenation is a simple task. You can do it in many ways by maintaining some basic concepts.

In the following section, 6 easy methods have been mentioned to concatenate strings in bash which include using the literal value of the string, command substitution, parameter expansion, using the += operator, printf command, and loop concatenation. Let’s take a look at the methods of concatenation:

1. Using the Literal Value of the String

The literal value of a string refers to the exact sequence of characters of the string without variable substitution or expansion. To preserve the literal value of the characters of the string, use single quotes(‘ ‘) which will not allow the command substitution and expansion.

To concatenate two strings with their literal values use the following code:

#!/bin/bash

concatenated_string='Hello''World'
echo $concatenated_string
EXPLANATION

The lineconcatenated_string='Hello''World'mainly concatenates the value within the single quotes and stores it in the new variable named concatenated_string.

Concatenate string using literal value of string

From the output, you can see I have appended the literal values one after another.

Concatenating Multiple Variable

Using these simple literal values you can also concatenate multiple variables into a string. Here is how:

#!/bin/bash

concatenated_string="Hello"This_the_first_string"World"
echo "$concatenated_string"
EXPLANATION

Theconcatenated_string="Hello"This_the_first_string"World"concatenates the strings and is assigned to the concatenated_string variable.

Multiple strings are concatenated in bash

The output shows the concatenated string. But it should be in mind that if it carries space in the string that is not inside quotes, then it will not show the expected result.

To concatenate multiple strings or variables using the command substitution or parameter expansion, follow the below syntax:

  1. Command substitution:
    string="$string1$string2$string3$string4"
  2. Parameter Expansion:
    string=${string1}${string2}${string3}${string4}

2. Using Command Substitution

Command substitution is used to include the result of a command within another command or expression. It is denoted with $(). With command substitution, you can join multiple strings to create a longer string. You can also use or insert the output of a command into a string using command substitution.

To concatenate the strings using command substitution, place the strings side by side. Here is how:

#!/bin/bash 

string1="The first line of the string. " 
string2="The second line of the string." string="$string1$string2"

echo $string
EXPLANATION

The"$string1$string2"concatenates the string in the variables string1 and string2. The concatenated is assigned to a new variable named string.

Concatenate two strings by placing side by side

Here I have concatenated two strings using command substitution and printed it on the terminal.

Concatenating Two Numbers

To concatenate two numbers by converting them into strings, you can use command substitution. Take a look at the following code:

#!/bin/bash

String1="1234"
String2="4578"
String3=$String1$String2

echo "$String3"
EXPLANATION

The value ofstring1andstring2is concatenated by placing one after another using command substitution and storing the final value in string3.

Two numbers are concatenated using command substituition

The output shows the concatenated string of two string numbers.

Using HEREDOC to Concatenate Strings in Multiline

Here document is a way to define multiline strings. You can use it to concatenate a string into the existing multiline string with command substitution.

To concatenate strings using heredoc look at the following code:

#!/bin/bash

# Initial string
original_string="This is the original string."

# Concatenate with another string using a here document
new_string=$(cat <<EOF
$original_string
This is the additional string.
EOF
)

echo "$new_string"
EXPLANATION

Withcat <<EOFthe here document has been started. In the here document, the value of the original_stringhas been inserted using variable substitution. WithEOFthe here doc has been ended. Using the variable substitution, the concatenated string has been stored in the new_string. With the echo command, the new string has been printed.

Concatenate a string with multiline string

In the here doc the first line is the original string which is declared before the heredoc starts. The additional string is also stored after the original string.

3. Using Parameter Expansion

The parameter expansion is the process of manipulating the values of a variable. The basic syntax is ${variable} which is the variable substitution. To concatenate two or more strings you can place the string one after another using the basic syntax of the parameter expansion. Here is how:

#!/bin/bash

echo "Using Listing"

string1="The first string."
string2="This is a new string."
concatenated_string=${string1}${string2}

echo "Concatenated String:$concatenated_string"
EXPLANATION

Two strings are assigned to the string1 and string2 variables. The${string1}${string2} concatenates two strings by placing the strings side by side using parameter expansion.

Using parameter expansion merge two string

From the output, you can see the string is on the right side of the first string.

Concatenate String with Variable

To concatenate a variable with a string, you can use the parameter expansion. Here is how:

#!/bin/bash

String1="Hello, "
String2="${String1}World"

echo "$String2"
EXPLANATION

The first string is assigned to the string1variable. The${String1} is the parameter expansion. The string “World” is concatenated with the value of  string1.

Concatenate a string and a variable

Like the above image, you can also replace the variable with numbers or special characters.

4. Using the “+=” Operator

You can use the “+=” operator for string concatenation in bash. It appends the new string to the right of the existing string.

To concatenate two strings using the += operator copy the following code:

#!/bin/bash

echo "Using Simple Concatenation"

string="Hello"
string+="1234"
concatenated_string="$string"

echo "Concatenated String:$concatenated_string"
EXPLANATION

Here, the new string 1234 is concatenated after the Hello using the+=operator. Without changing the existing string, the operator mainly appended the new string to the right of the existing string.

Concatenate two strings in bash with operator

In this process, I have used a number as a string. If you don’t want to use the double quotes while appending numbers, you can do that as there is no space between them. But it is better to use double quotes (” “).

5. String Concatenation with “printf” Command

The printf command is mainly used for formatting the output. You can use printf for string concatenation by formatting them and storing the output to a new string.

To concatenation strings using printf, use the following code:

#!/bin/bash

string1="Hello,"
string2="This is a special character (*)"

printf "%s %s\n" "$string1" "$string2"
EXPLANATION

Two strings are declared as string1 and string2. In theprintfcommand, the%sis the placeholder for the string. And\nis used to create a new line after the output.

Two string Concatenation with printf command

From the output, you can see by following this method, you can concatenate two strings one after another.

6. Using Loop to Concatenate Strings

You can use loop to concatenate a string multiple times before or after each element of the input string. At the end of the loop, you can find that the input string will contain the repetitive string.

To concatenate a single string multiple times into an input string, you can use a loop. Here is how:

#!/bin/bash

input_string="Multiple methods of concatenation"
newstring=""

for i in $input_string
do
newstring+="Using loop $i "
done

echo $newstring
EXPLANATION

With input<strong>_</strong>string="Multiple methods of concatenation", a new string is declared. An empty string is declared as a new string. The for loop iterates over each word of the string and concatenates “Using loop” before each word.

Bash string concatenation using loop

From the above image, you can see that I have concatenated a string into another string multiple times using a loop.

Concatenation String in an Array

To concatenate a string with each element of an array, follow the code shown below:

#!/bin/bash

array=("Lang1" "Lang2" "Lang3")  # Replace with your actual values
new=""

for i in "${array[@]}"
do
new+="Using loop $i... "
done

echo $new
EXPLANATION

An array has been declared with three elements in this linearray=("Lang1" "Lang2" "Lang3"). The new_string has the concatenated string. In each iteration, the loop adds elements with the text"Using loop"and stores them in the new variable.

Concatenation of string into array using loop

By using this method, you can append a specific string after each of the strings.

Practical Examples of String Concatenation

You can use string concatenation in several practical scenarios like constructing file names with format or types, merging multiple strings to a new file, constructing meaningful email IDs, or even generating CSV files. Here are 4 examples to do so:

1. Creating Photograph Name

To create a photograph name with format and date of modification, use the following code:

#!/bin/bash

# Concatenating strings to create photo name
file_prefix="photo"
file_suffix=".jpg"
file_name="${file_prefix}_$(date +%Y%m%d)${file_suffix}"
EXPLANATION

The previous and post string has been declared with file_prefix and file_suffix. With the command substitution, the date has been appended to the new string. The%Y%m%drefers to the format specifier that has been used with the date command and it represents the current year, month, and date in this specific format. The character_between the photo and date is used to concatenate the strings.

Using concatenation in bash create a photo name with date

2. Save Multiline into a New File

To save the concatenated new multiline string which you can create using the heredoc into a new file, use the following code:

#!/bin/bash

cat <<EOF > output.txt
The name of the current user is $(whoami)
Today’s date:$(date)
EOF
EXPLANATION

With cat <<EOF > output.txt, heredoc creates a multiline string which will be saved to the output.txt file with the redirection > symbol. The heredoc has the current user name and today’s date with the help of the whoami command and date command. The EOF indicates the end of the here document.

Save string from heredoc into a file in bash string concatenation

The output.txt file shows the saved output of the heredoc.sh script.

3. Constructing Email Addresses

To construct an email address, you can use string concatenation and also append @ in the email address. Here is how:

#!/bin/bash

# Concatenating strings to construct email addresses
user_name="john.doe"
domain="example.com"
email_address="${user_name}@${domain}"

echo "Email Address: $email_address"
EXPLANATION

In theemail_address="${user_name}@${domain}", all the strings are previously declared, and @is also appended by placing this at the side of the strings.

Create a email address using string concatenation

4. Generating CSV File

To generate a CSV file, you can use string concatenation. Take a look at the following code:

#!/bin/bash 

# Concatenating strings with newline for CSV content header="Name, Age, Occupation" 
data_row1="John Doe, 30, Engineer" 
data_row2="Jane Smith, 25, Doctor" 

csv_content="${header}\n${data_row1}\n${data_row2}" 

echo -e "$csv_content" > data.csv
EXPLANATION

All the strings are declared in variables. Incsv_content="${header}\n${data_row1}\n${data_row2}", all the variables are separated with newline characters. The concatenated string is stored incsv_content. In the echo command, the-eoption has been used to interpret the backslash escapes. The redirection operator (>) has redirected the content to the CSV file.

Creating a csv file using concatenation

Executing the bash script, use the ls command to see the new CSV file. Below you can see the content of the newly created string:

Showing the csv file which has columns and rows

The output shows a CSV file that includes 3 columns and 3 rows with the variable name.

Conclusion

The article shows different methods to concatenate strings. In all of these methods placing strings side by side or in a specific position with command substitution and parameter expansion increases the flexibility and versatility of the practical use of string concatenation. The other methods also give flexibility like placing strings next to each other. I hope the users will benefit by gathering the ideas of string concatenation from this article.

People Also Ask

Can I create log files using string concatenation?

Yes, you can create log files using concatenation. Use the following code to create log files:

#!/bin/bash

# Concatenating date to create log file names

log_prefix="app_log"
date_extension=$(date +"%Y%m%d")
log_file_name="${log_prefix}_${date_extension}.log"

echo "Log File Name: $log_file_name"

With the .log extension, a log file name has been created. In the log file name, the underscore (_) is also appended in the string.

How to concatenate two arrays into a single array?

To concatenate two arrays, first declare the two arrays which contain 3 elements. Then concatenate the arrays using variable substitution. Here is how:

#!/bin/bash

# Declare two arrays
array1=("apple" "banana" "cherry")
array2=("orange" "grape" "kiwi")

# Concatenate arrays
concatenated_array=("${array1[@]}" "${array2[@]}")

# Print the concatenated array elements
echo "Concatenated Array: ${concatenated_array[@]}"

To print the concatenated array, you can use the echo command.

How to concatenate string to comma-separated element?

To concatenate a specific string into a comma-separated string, use the following code:

#!/bin/bash

# Comma-separated string
comma_separated="apple,banana,cherry"

# String to concatenate
suffix="_fruit"

# Convert comma-separated string to an array
IFS=',' read -ra elements <<< "$comma_separated"

# Concatenate the string to each element
for ((i=0; i<${#elements[@]}; i++)); do
elements[$i]="${elements[$i]}$suffix"
done

# Reconstruct the comma-separated string
concatenated_string=$(IFS=, ; echo "${elements[*]}")

# Print the result
echo "Concatenated String: $concatenated_string"

In the code, the comma-separated string has been split using the Internal Field Separator into elements. The for loop iterates over each element and appends the suffix with each element.

How to insert characters in a string in bash?

To insert characters or strings into a specific position of a string, use the following code:

#!/bin/bash

original_string="This is a sample string."

# Define the position where characters should be inserted
position=10

# Insert characters (in this case, "INSERTED ") at the specified position
modified_string="${original_string:0:position}INSERTED ${original_string:position}"

echo "Original String: $original_string"
echo "Modified String: $modified_string"

Here I have appended a specific string “INSERTED” to the string at the position of 10.

Can I use space, underscore, and newline characters in string concatenation?

Yes, you can use space, underscore, and newline characters in string concatenation. Take a look at the code shown below:

#!/bin/bash

string1="The first line of the string. "
string2="The second line of the string."
string="$string1$string2"

echo $string

In this code within the double quotation, you can use the special characters in between the strings at any specific position of the string.

Can I concatenate strings using join?

Yes, you can concatenate two file strings with the join command. But in this process, the number of columns of the two files should match otherwise it won’t show the expected result. For the join command, here is how the code looks:

join string1.txt string2.txt

The join command mainly joins strings from two files based on the common field. If it does not find any command field then it won’t show the expected result.

Related Articles


<< Go Back to Bash String Operations | Bash String | Bash Scripting Tutorial

Rate this post
LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now
icon linux
Afia Zahin Oishi

Assalamualaikum, I am Afia Zahin, completed my graduation in Biomedical Engineering from Bangladesh University of Engineering and Technology, currently working as a Linux Content Developer Executive at SOFTEKO. A high achieving professional with a strong work ethic and able to work in a team in order to consistently achieve my goal and build my skillset. Able to handle difficult problems with patience and swift decision-making. Read Full Bio

Leave a Comment