How to Concatenate Strings in Bash: Simple Syntax and Examples
In Bash, you concatenate strings simply by placing them next to each other, like
str1="Hello" and str2="World", then result="$str1$str2". You can also add spaces or other characters between strings by including them inside the quotes.Syntax
To join strings in Bash, you just write them one after another inside double quotes or variables. No special operator is needed.
str1="Hello": Assign first string.str2="World": Assign second string.result="$str1$str2": Concatenate both strings.
bash
str1="Hello" str2="World" result="$str1$str2" echo "$result"
Output
HelloWorld
Example
This example shows how to join two strings with a space between them by adding a space character inside the quotes.
bash
greeting="Hello" name="Alice" full_greeting="$greeting, $name!" echo "$full_greeting"
Output
Hello, Alice!
Common Pitfalls
One common mistake is forgetting to use double quotes around variables, which can cause word splitting or unexpected results. Another is trying to use the plus sign + like in other languages, which does not work in Bash.
bash
# Wrong way (will not concatenate): str1="Hello" str2="World" result=$str1$str2 echo "$result" # Right way: result="$str1$str2" echo "$result"
Output
HelloWorld
HelloWorld
Quick Reference
Remember these tips for string concatenation in Bash:
- Place variables side by side inside double quotes to join.
- Add spaces or punctuation inside quotes as needed.
- Always quote variables to avoid word splitting.
- Do not use
+for concatenation.
Key Takeaways
Concatenate strings by placing variables side by side inside double quotes.
Include spaces or punctuation inside quotes to format the result.
Always quote variables to prevent word splitting and errors.
Do not use plus signs (+) for string concatenation in Bash.