BudiBadu Logo
Samplebadu

Bash by Example: String Concatenation

Bash 5.0+

Joining strings in Bash is as simple as placing them side-by-side. This sample code shows various concatenation techniques.

Code

#!/bin/bash

first="Hello"
second="World"

# Simple concatenation
greeting="$first $second"
echo "$greeting"

# Concatenating without spaces
filename="backup"
ext=".tar.gz"
fullname="${filename}${ext}"
echo "File: $fullname"

# Appending to a variable using +=
path="/usr/bin"
path+=":/usr/local/bin"
echo "Path: $path"

# Using printf for formatted concatenation
printf -v formatted_msg "User: %s, ID: %d" "Alice" 1001
echo "$formatted_msg"

Explanation

String concatenation in Bash does not require a specific operator like + or . found in other languages. Instead, you simply place variables or string literals next to each other. The shell expands the variables and joins the results.

When concatenating variables directly without separators, it is best practice to use curly braces ${var}. This prevents the shell from confusing the variable name with the text that follows it (e.g., trying to read $filenameext instead of $filename followed by ext).

You can also append to a string using the += operator, which is cleaner than reassigning the variable to itself. For more complex formatting, the printf command is powerful, allowing you to format strings similar to C's printf and store the result in a variable using the -v flag.

Code Breakdown

7
Concatenation with a space. The shell expands $first to "Hello", sees the space literal, expands $second to "World", and assigns the combined result "Hello World" to greeting.
13
Concatenation without separators. We use ${filename} to explicitly delimit the variable name. While $filename$ext would also work here because $ starts a new token, using braces is a safer habit.
18
path+=":/usr/local/bin" appends the string to the existing variable. This is more efficient and readable than path="$path:/usr/local/bin".
22
printf -v formats the string and stores it directly in the variable formatted_msg instead of printing to stdout.