How to Concatenate Strings in Bash
Quick Answer: Concatenate Strings in Bash
To join strings in Bash, simply place them next to each other: result="$first $second". Bash automatically concatenates adjacent strings and variables. For more control or complex cases, use the += operator for appending or printf for formatting.
Quick Comparison: String Concatenation Methods
| Method | Speed | Best For | Complexity |
|---|---|---|---|
| Variable expansion | Fastest | Simple joining | Very simple |
| += operator | Very fast | Building strings incrementally | Simple |
| printf | Very fast | Formatted output | Moderate |
| echo with concatenation | Fast | Output directly | Simple |
| String interpolation | Very fast | Complex formatting | Moderate |
Bottom line: Use simple variable expansion for most cases. Use printf when you need formatting control.
Method 1: Variable Expansion (Simplest)
Variable expansion is the fastest and most natural way to concatenate strings in Bash. Simply place variables and strings next to each other, and Bash automatically joins them. No special operators or commands needed. This works because Bash treats adjacent strings as a single unit when they’re in the same context.
Basic Concatenation
Here’s the fundamental pattern—just put your variables together:
first="Hello"
second="World"
result="$first $second"
echo "$result"
# Output: Hello World
Notice how we put $first and $second next to each other with a space between them. Bash concatenates them into a single string. This is the go-to method for most string joining tasks.
Concatenation Without Spaces
When you don’t want space between parts, put them directly together:
greeting="Hello"
name="Alice"
message="$greeting, $name!"
echo "$message"
# Output: Hello, Alice!
The string is built exactly as written—variables are substituted in place, and the result is a single string. No spaces are added automatically, so you control the spacing.
When to Use Variable Expansion
Use variable expansion when:
- You’re joining a few strings (simple cases)
- You need the fastest performance
- You want readable, straightforward code
- You’re building strings in a single context (like
"$var1$var2$var3") - You don’t need complex formatting
Don’t use it when:
- You’re building strings in a loop incrementally (use
+=instead) - You need formatted output with padding or alignment (use
printf) - You’re joining many strings (consider using
printffor clarity)
Method 2: Using += Operator (For Building Strings)
The += operator is perfect when you’re building a string incrementally, adding parts one at a time. This is common in loops or when you’re constructing a string based on conditions.
Appending Strings
The += operator appends to an existing variable:
text=""
text+="Hello"
text+=" "
text+="World"
echo "$text"
# Output: Hello World
Each += adds more content to the string. This is clearer than repeatedly reassigning like text="$text Hello", which is slower because it creates a new string each time.
Building Strings in Loops
This is where += really shines—when you’re adding multiple pieces conditionally or in a loop:
output=""
for item in apple banana orange; do
output+="$item "
done
echo "$output"
# Output: apple banana orange
Without +=, you’d have to write output="$output $item", which creates intermediate strings. The += operator is clearer and slightly more efficient.
When to Use +=
Use += when:
- Building strings incrementally (especially in loops)
- Adding content to an existing string
- You want clear, readable code that shows you’re adding to something
- Constructing output based on conditions
Avoid it when:
- Creating a simple concatenation on one line (use variable expansion)
- You need formatted output (use
printf)
Method 3: Using printf (For Formatted Output)
Use printf when you need formatted output with padding, alignment, or specific formatting. Printf is more powerful than simple concatenation when you care about spacing or number formatting.
Basic printf Concatenation
Here’s how to use printf to format and concatenate:
first="Hello"
second="World"
result=$(printf "%s %s" "$first" "$second")
echo "$result"
# Output: Hello World
Printf takes a format string ("%s %s" means two strings separated by space) and the values to insert. This is useful when you want precise control over spacing and formatting.
Formatted Concatenation
Printf becomes really useful when you need specific formatting:
name="Alice"
age=30
message=$(printf "Name: %-15s Age: %d" "$name" "$age")
echo "$message"
# Output: Name: Alice Age: 30
The format string controls exact spacing. %-15s means “left-align the string in a 15-character field.” This is essential for creating aligned output.
When to Use printf
Use printf when:
- You need formatted output (padding, alignment, precision)
- You’re mixing different data types (strings, numbers, etc.)
- You want consistent spacing or field widths
- You’re building complex formatted strings
Skip it when:
- Simple concatenation is enough (variable expansion is faster)
- You don’t need special formatting
Method 4: Concatenate Array Elements
When you have multiple items in an array, you can join them into a single string. This is useful for converting array data into strings or creating comma-separated lists.
Join All Array Elements
Here’s how to concatenate all array elements into one string:
words=(Hello World from Bash)
result="${words[@]}"
echo "$result"
# Output: Hello World from Bash
The ${words[@]} expands to all elements separated by spaces (the default IFS). Each element is separated based on your IFS setting.
Join with Custom Separator
To use a custom separator (like comma), temporarily change IFS:
items=("apple" "banana" "orange")
result=$(IFS=','; echo "${items[*]}")
echo "$result"
# Output: apple,banana,orange
The ${items[*]} expands with the separator defined by IFS. Notice we use ; inside the command substitution to change IFS only for that operation—it doesn’t affect the rest of your script.
When to Use Array Concatenation
Use array element concatenation when:
- You already have an array you need to convert to a string
- You want to join list items with a specific separator
- You’re transforming data between array and string formats
Practical Examples
Example 1: Build File Path
#!/bin/bash
# Concatenate path components
dir="/home/user"
filename="documents.txt"
filepath="$dir/$filename"
echo "File path: $filepath"
# Output: File path: /home/user/documents.txt
This is simple variable expansion—the most common case for building paths. Just put the directory and filename together with a / between them.
Example 2: Build URL
#!/bin/bash
# Construct URL from parts
protocol="https"
domain="example.com"
path="/api/users"
url="$protocol://$domain$path"
echo "URL: $url"
# Output: URL: https://example.com/api/users
Again, simple concatenation. The variables are replaced in place, creating the final URL. This is more readable than building the URL inside quotes with all the parts.
Example 3: Build Query String
#!/bin/bash
# Build with += for clarity
query=""
query+="?name=John"
query+="&age=30"
query+="&city=NYC"
echo "Query: $query"
# Output: Query: ?name=John&age=30&city=NYC
Using += makes it clear you’re building the query string piece by piece. Each line adds a parameter.
Example 4: Build Command String
#!/bin/bash
# Build command arguments based on conditions
cmd="curl"
cmd+=" -X POST"
cmd+=" -H 'Content-Type: application/json'"
cmd+=" -d '{\"name\": \"John\"}'"
cmd+=" https://api.example.com/users"
echo "Command: $cmd"
# Output: Command: curl -X POST -H 'Content-Type: application/json' -d '{"name": "John"}' https://api.example.com/users
Using += to build a command line is more readable than one giant assignment, especially when you want to conditionally add parts.
Example 5: Build Multiline String
#!/bin/bash
# Build multiline string with +=
text="Line 1"
text+=$'\n' # Add newline (special syntax)
text+="Line 2"
text+=$'\n'
text+="Line 3"
echo "$text"
# Output:
# Line 1
# Line 2
# Line 3
The $'\n' syntax creates a literal newline character. Using += makes it clear you’re building the string across multiple lines.
Example 6: Build Log Message with Timestamp
#!/bin/bash
# Build formatted log message
timestamp=$(date "+%Y-%m-%d %H:%M:%S")
level="INFO"
message="User login successful"
log_entry="[$timestamp] $level: $message"
echo "$log_entry"
# Output: [2026-02-21 15:30:45] INFO: User login successful
Simple variable expansion for a structured log entry. The format is clear from the string template.
Quick Reference
# Simple concatenation
result="$var1 $var2"
# Without spaces
result="$var1$var2"
# Build incrementally
text=""
text+="part1"
text+="part2"
# Using printf for formatting
result=$(printf "%-10s %d" "$name" "$age")
# Join array with commas
result=$(IFS=','; echo "${array[*]}")
# Build paths
filepath="$dir/$file"
# Build URLs
url="$protocol://$domain$path"
Summary
For string concatenation, simple variable expansion is your go-to tool—it’s fast, readable, and handles most cases. Use += when building strings incrementally, and reach for printf only when you need formatted output with specific spacing or alignment. For most daily scripting tasks, you’ll find that putting variables next to each other in quotes gets the job done perfectly.