0
0
Bash-scriptingHow-ToBeginner · 2 min read

Bash Script to Remove Spaces from String

Use echo "$string" | tr -d ' ' in Bash to remove all spaces from a string.
📋

Examples

Inputhello world
Outputhelloworld
Input spaced out string
Outputspacedoutstring
Inputnospace
Outputnospace
🧠

How to Think About It

To remove spaces from a string in Bash, think of filtering out the space characters. You can do this by passing the string through a command that deletes spaces, like tr -d ' ', which removes all spaces from the input.
📐

Algorithm

1
Get the input string.
2
Use a command to delete all space characters from the string.
3
Output the resulting string without spaces.
💻

Code

bash
#!/bin/bash

string="hello world from bash"
result=$(echo "$string" | tr -d ' ')
echo "$result"
Output
helloworldfrombash
🔍

Dry Run

Let's trace the string 'hello world from bash' through the code

1

Input string

string = 'hello world from bash'

2

Remove spaces

echo "$string" | tr -d ' ' => 'helloworldfrombash'

3

Output result

result = 'helloworldfrombash' printed

StepString Value
Initialhello world from bash
After tr -d ' 'helloworldfrombash
💡

Why This Works

Step 1: Echo the string

The echo command outputs the string so it can be processed.

Step 2: Delete spaces

The tr -d ' ' command deletes all space characters from the input.

Step 3: Store and print

The result is stored in a variable and printed without spaces.

🔄

Alternative Approaches

Using parameter expansion
bash
#!/bin/bash
string="hello world from bash"
result="${string// /}"
echo "$result"
This method uses Bash's built-in string replacement and is faster since it avoids external commands.
Using sed
bash
#!/bin/bash
string="hello world from bash"
result=$(echo "$string" | sed 's/ //g')
echo "$result"
This uses <code>sed</code> to globally remove spaces but is slower than parameter expansion.

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

Time Complexity

The operation scans each character once to remove spaces, so it runs in linear time relative to string length.

Space Complexity

A new string without spaces is created, so space used is proportional to the input string size.

Which Approach is Fastest?

Parameter expansion is fastest as it avoids spawning external processes, while tr and sed are slower due to command execution overhead.

ApproachTimeSpaceBest For
Parameter ExpansionO(n)O(n)Fastest, pure Bash
tr -d ' 'O(n)O(n)Simple and readable
sed substitutionO(n)O(n)Flexible pattern removal
💡
Use Bash parameter expansion ${string// /} for the fastest space removal without external commands.
⚠️
Forgetting to quote the variable can cause word splitting and unexpected results.