How to concatenate string variables in Bash

Learn how to concatenate string variables in bash with practical examples, diagrams, and best practices. Covers bash, shell, syntax development techniques with visual explanations.

Mastering String Concatenation in Bash

Hero image for How to concatenate string variables in Bash

Learn the various methods to combine string variables in Bash, from simple direct assignment to advanced techniques, ensuring robust shell scripting.

String concatenation is a fundamental operation in any programming or scripting language, and Bash is no exception. Whether you're building file paths, constructing command arguments, or generating dynamic output, knowing how to effectively combine strings is crucial for writing powerful and flexible shell scripts. This article will guide you through the most common and effective ways to concatenate strings in Bash, along with best practices and common pitfalls.

Basic Concatenation: Direct Assignment

The simplest and most common way to concatenate strings in Bash is by placing variables and literal strings next to each other. Bash automatically performs concatenation when it encounters adjacent strings or variables within a command or assignment. No special operators are needed for this basic form of concatenation.

#!/bin/bash

# Define some string variables
part1="Hello"
part2="World"

# Concatenate using direct assignment
full_string="$part1 $part2"
echo "Method 1: $full_string"

# Concatenate with literal strings
message="The answer is "
value=42
result="$message$value"
echo "Method 2: $result"

# Concatenate multiple variables and literals
path_prefix="/home/user"
filename="document.txt"
full_path="$path_prefix/$filename"
echo "Method 3: $full_path"

Examples of basic string concatenation using direct assignment.

Concatenation with += Operator (Bash 3.1+)

For appending a string to an existing variable, Bash offers the += operator, similar to how it's used with arithmetic operations. This operator is particularly useful when you need to build up a string iteratively or append content to a variable that already holds a value. This feature was introduced in Bash version 3.1, so be mindful of compatibility if targeting older systems.

#!/bin/bash

# Initialize a string
my_string="Initial content"
echo "Original: $my_string"

# Append a new string
my_string+=" - Appended content"
echo "After append 1: $my_string"

# Append another string with a variable
new_part=" and more!"
my_string+="$new_part"
echo "After append 2: $my_string"

# Append a newline character
my_string+="\nThis is a new line."
echo -e "After newline: $my_string"

Using the += operator to append strings to an existing variable.

flowchart TD
    A[Start]
    B{Initialize String}
    C[Append String 1]
    D[Append String 2 (Variable)]
    E[Append Special Character (e.g., Newline)]
    F[End]

    A --> B
    B --> C
    C --> D
    D --> E
    E --> F

Workflow for building a string iteratively using the += operator.

Concatenation with Command Substitution

Command substitution allows the output of a command to be used as part of a string. This is incredibly powerful for dynamic string construction, where parts of your string come from external commands or scripts. You can use either backticks `command` or the more modern $(command) syntax. The latter is generally preferred as it handles nesting better and is easier to read.

#!/bin/bash

# Get current date
current_date=$(date +%Y-%m-%d)

# Get current user
current_user=$(whoami)

# Concatenate with command substitution
log_entry="Log entry for $current_user on $current_date: Operation completed."
echo "$log_entry"

# Example with backticks (less preferred)
file_count="There are `ls -l | wc -l` files in the current directory."
echo "$file_count"

Concatenating strings using command substitution to include dynamic data.