To concatenate string variables in Bash, you can use the following methods:
1. Basic Concatenation
Place variables/literals adjacent to each other:
str1="Hello"
str2="World"
result="$str1 $str2!" # Output: "Hello World!"
2. Using +=
Operator
Append to an existing variable:
greeting="Hello"
greeting+=" World" # greeting becomes "Hello World"
3. With Literal Text
Mix variables and strings:
name="Alice"
message="Hello, $name! Today is $(date)" # Includes command substitution
4. Using printf
(For Formatting)
Control the output format:
first="John"
last="Doe"
printf -v full_name "%s, %s" "$last" "$first" # full_name="Doe, John"
5. Concatenate in a Loop
Build a string incrementally:
parts=("I" "am" "learning" "Bash")
sentence=""
for part in "${parts[@]}"; do
sentence+="$part "
done # sentence="I am learning Bash "
Key Notes
- Always quote variables to handle spaces/special characters:
# Bad (breaks with spaces):
result=$str1$str2
# Good:
result="$str1$str2"
- Use
${var}
to avoid ambiguity:
animal="cat"
echo "I have a ${animal}tail" # Without braces: "I have a cattail"
Examples
Concatenate with a Separator
dir_path="/home/user"
file="document.txt"
full_path="$dir_path/$file" # "/home/user/document.txt"
Combine Variables and Commands
user="$USER"
timestamp=$(date +%s)
log_entry="User $user logged at $timestamp"
Summary
Method | Use Case | Example |
---|---|---|
Adjacent | Simple concatenation | result="$str1$str2" |
+= | Append to existing strings | str+=" new text" |
printf | Format strings with precision | printf -v var "..." |
Loop | Build strings incrementally | for ...; do str+="..." |
By following these patterns, you can safely concatenate strings in Bash scripts.