0
0
Bash-scriptingHow-ToBeginner · 2 min read

Bash Script to Concatenate Two Strings Easily

In Bash, you can concatenate two strings simply by placing them next to each other like result="$string1$string2".
📋

Examples

Input"Hello", "World"
OutputHelloWorld
Input"Good", " Morning"
OutputGood Morning
Input"", "Empty"
OutputEmpty
🧠

How to Think About It

To concatenate two strings in Bash, think of joining them side by side without any operator needed. Just place the variables or strings next to each other inside quotes to combine them into one.
📐

Algorithm

1
Get the first string input.
2
Get the second string input.
3
Combine both strings by placing them next to each other.
4
Store the combined result in a new variable.
5
Print the combined string.
💻

Code

bash
#!/bin/bash
string1="Hello"
string2="World"
result="$string1$string2"
echo "$result"
Output
HelloWorld
🔍

Dry Run

Let's trace concatenating "Hello" and "World" through the code

1

Assign string1

string1="Hello"

2

Assign string2

string2="World"

3

Concatenate strings

result="Hello" + "World" = "HelloWorld"

4

Print result

Output: HelloWorld

StepVariableValue
1string1Hello
2string2World
3resultHelloWorld
💡

Why This Works

Step 1: Variable assignment

Assign the first and second strings to variables using = without spaces.

Step 2: Concatenation

Combine strings by placing variables side by side inside double quotes with "$string1$string2".

Step 3: Output

Use echo to print the combined string to the terminal.

🔄

Alternative Approaches

Using printf
bash
#!/bin/bash
string1="Hello"
string2="World"
printf "%s%s\n" "$string1" "$string2"
This method formats and prints strings without creating a new variable, useful for direct output.
Using += operator
bash
#!/bin/bash
string1="Hello"
string1+="World"
echo "$string1"
This appends the second string directly to the first variable, modifying it in place.

Complexity: O(1) time, O(n) space

Time Complexity

Concatenation is a simple operation done once, so it runs in constant time O(1).

Space Complexity

Requires space proportional to the combined length of both strings, O(n), where n is total characters.

Which Approach is Fastest?

All methods run in constant time; using += modifies in place, slightly saving memory.

ApproachTimeSpaceBest For
Simple concatenationO(1)O(n)General use, clear code
printf methodO(1)O(n)Direct formatted output without extra variables
+= operatorO(1)O(n)Appending to existing variable efficiently
💡
Always use double quotes around variables to preserve spaces and special characters when concatenating.
⚠️
Forgetting to quote variables can cause word splitting or unexpected results during concatenation.