
String concatenation is a core concept in Bash scripting that lets you join multiple text fragments into a single string. It’s essential for tasks like building file paths, composing dynamic messages, and assembling command-line arguments or configuration lines within shell scripts.
This article explains various ways to concatenate strings in Bash, including simple variable joining, using curly brace notation for clarity, formatting numbers alongside text, and assembling structured strings with loops. These techniques help you write flexible, readable, and maintainable Bash scripts.
Concatenation of Multiple Variables
Bash allows you to concatenate strings by directly placing variables next to each other or by using curly braces for clarity and control.
Basic Variable Concatenation
Create a script file.
console$ nano basic_concatenation.sh
Add the following content to the file:
bash#!/bin/bash # Basic string concatenation examples first_name="John" # Given name last_name="Doe" # Surname domain="example.com" # Domain used for building an email address full_name_spaced="$first_name $last_name" # Concatenate with a literal space echo "Full name: $full_name_spaced" email="$first_name.$last_name@$domain" # Join with '.' and '@' to form an email echo "Email: $email"
Save and close the file.
Make the script executable.
console$ chmod +x basic_concatenation.sh
Run the script.
console$ ./basic_concatenation.sh
Output:
Full name: John Doe Email: John.Doe@example.com
Using Curly Braces for Safer Expansion
Create a second script.
console$ nano advanced_concatenation.sh
Add the following content to the file:
bash#!/bin/bash # Demonstrates brace expansion for safe concatenation prefix="server" # Text prefix for the resource name number="01" # Zero-padded sequence as a string suffix="prod" # Environment tag server_name="${prefix}_${number}_${suffix}" # ${var} makes variable boundaries unambiguous; '_' is a literal separator echo "Server name: $server_name"
Save and close the file.
Make the script executable.
console$ chmod +x advanced_concatenation.sh
Run the script.
console$ ./advanced_concatenation.sh
Output:
Server name: server_01_prod
Concatenation of Numbers and Strings
Bash lets you combine numeric values with strings to create URLs, IDs, version tags, or other formatted output. You can insert variables into strings directly or use arithmetic expressions to calculate and embed results.
Combine Numbers with Text
Create a script file.
console$ nano number_concatenation.sh
Add the following content to the file:
bash#!/bin/bash # Build a URL by concatenating protocol, hostname, and port port=8080 # Numeric port; will be treated as a string during concatenation protocol="https" # Scheme hostname="www.example.com" # Hostname under example.com url="${protocol}://${hostname}:${port}" # Use ${} to avoid ambiguity next to ':' and '/' echo "Complete URL: $url"
Save and close the file.
Make the script executable.
console$ chmod +x number_concatenation.sh
Run the script.
console$ ./number_concatenation.sh
Output:
Complete URL: https://www.example.com:8080
Arithmetic in Concatenation
Create a new script file.
console$ nano arithmetic_concatenation.sh
Add the following content to the file:
bash#!/bin/bash # Demonstrates arithmetic expansion and string concatenation base_number=100 # Integer operand increment=25 # Integer operand result=$((base_number + increment)) # $(( )) performs integer arithmetic; spaces are allowed inside message="The result of $base_number + $increment is $result" # Insert values into a string echo "$message" id_prefix="USER" # String prefix for IDs id_number=1001 # Current numeric ID next_id=$((id_number + 1)) # Arithmetic expansion to get the next ID current_user_id="${id_prefix}_${id_number}" # Use ${} for clear boundaries; '_' is a literal next_user_id="${id_prefix}_${next_id}" echo "Current user: $current_user_id" echo "Next user: $next_user_id"
Save and close the file.
Make the script executable.
console$ chmod +x arithmetic_concatenation.sh
Run the script.
console$ ./arithmetic_concatenation.sh
Output:
The result of 100 + 25 is 125 Current user: USER_1001 Next user: USER_1002
Concatenation of Numeric Strings
You can format and join numeric values stored as strings in Bash to generate dates, timestamps, prices, and other structured outputs.
Create a script file.
console$ nano numeric_strings.sh
Add the following content to the file:
bash#!/bin/bash # Numeric values stored as strings and concatenated in different formats num1="42" # First numeric string num2="17" # Second numeric string concatenated="$num1$num2" # Simple concatenation: no operator needed in Bash echo "Concatenated: $concatenated" with_separator="$num1-$num2" # Concatenate with a literal '-' separator echo "With separator: $with_separator" price="99" # Whole dollar part as a string cents="95" # Cents part as a string formatted_price="\$${price}.${cents}" # Escape $ as \$ to print a literal dollar sign; ${} clarifies boundaries echo "Price: $formatted_price" hour="09" # Zero-padded hour minute="05" # Zero-padded minute time_formatted="${hour}:${minute}" # Use ':' as a literal separator echo "Time: $time_formatted"
Save and close the file.
Make the script executable.
console$ chmod +x numeric_strings.sh
Run the script.
console$ ./numeric_strings.sh
Output:
Concatenated: 4217 With separator: 42-17 Price: $99.95 Time: 09:05
Concatenation Using for
Loops
You can use for
loops in Bash to iteratively build strings from arrays, ideal for generating lists, CSV headers, or formatted content.
Create a script file.
console$ nano loop_concatenation.sh
Add the following content to the file:
bash#!/bin/bash # Build comma-separated strings from arrays servers=("web01" "web02" "web03" "db01" "cache01") # Array of server names all_servers="" # Accumulator starts empty for server in "${servers[@]}"; do # "${array[@]}" preserves elements with spaces if [ -z "$all_servers" ]; then # -z tests for an empty string all_servers="$server" else all_servers="$all_servers, $server" # Append with a leading comma and space fi done echo "All servers: $all_servers" fields=("Name" "Age" "Email" "Department") # Array of column names csv_header="" # Header accumulator for field in "${fields[@]}"; do if [ -z "$csv_header" ]; then csv_header="$field" else csv_header="$csv_header,$field" # Join with commas, no trailing comma fi done echo "CSV Header: $csv_header"
Save and close the file.
Make the script executable.
console$ chmod +x loop_concatenation.sh
Run the script.
console$ ./loop_concatenation.sh
Output:
All servers: web01, web02, web03, db01, cache01 CSV Header: Name,Age,Email,Department
Conclusion
In this article, you explored multiple techniques for string concatenation in Bash. You learned how to combine text using direct placement and curly brace notation, append numbers to strings for building URLs or identifiers, format numeric strings cleanly, and construct complex output using for
loops.
These techniques allow you to generate dynamic values and maintain readable scripts for automation, logging, and configuration tasks. For additional reference, consult the Bash manual.
No comments yet.