
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.
Bash allows you to concatenate strings by directly placing variables next to each other or by using curly braces for clarity and control.
Create a script file.
Add the following content to the file:
Save and close the file.
Make the script executable.
Run the script.
Output:
Create a second script.
Add the following content to the file:
Save and close the file.
Make the script executable.
Run the script.
Output:
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.
Create a script file.
Add the following content to the file:
Save and close the file.
Make the script executable.
Run the script.
Output:
Create a new script file.
Add the following content to the file:
Save and close the file.
Make the script executable.
Run the script.
Output:
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.
Add the following content to the file:
Save and close the file.
Make the script executable.
Run the script.
Output:
for LoopsYou 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.
Add the following content to the file:
Save and close the file.
Make the script executable.
Run the script.
Output:
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.
0 Comments
Be the first to comment and share your perspective with the community.