Working With Strings in Bash
14 min read·Feb 24, 2025
In programming, strings are one of the most commonly used data types.
In the context of Bash, string manipulation is crucial as many tasks involve processing text in files, environment variables, or command outputs.
Concatenating strings
In programming, concatenating strings refers to the process of linking together multiple strings into a single one.
It is mostly used to combine directory paths and filenames to dynamically create full paths, create formatted strings for logs or user feedback, generate URLs with query parameters or endpoints, and so on.
To concatenate multiple strings contained in variables, you can enclose the value of these variables in double quotes:
"$variable_A$variable_B"
💡 Reminder: To access the value of a variable in Bash, you must prepend it with a dollar sign
$.
Example
Let's consider this script located in the ~/scripts directory, that outputs its own content:
#!/bin/bash
directory="$HOME/scripts"
file="reflect.sh"
path="$directory/$file"
cat $path
When executed, it will:
- Define a variable named
directoryand initialize it with the value of theHOMEenvironment variable concatenated to the"/scripts"string. - Define a variable named
fileand initialize it with the string"reflect.sh". - Define a variable named
pathand initialize it with the concatenated values of thedirectoryandfilevariables. - Output the content of the file located at the path contained in the
pathvariable using thecatcommand.
Which will produce this output:
$ ./reflect.sh
#!/bin/bash
directory="$HOME/scripts"
file="reflect.sh"
path="$directory/$file"
cat $path
Appending strings to variables
To add a string at the end of another string contained in a variable, you can use the += operator:
variable+=value
Example
Let's consider this script, that outputs user information passed through positional arguments in a formatted manner:
#!/bin/bash
output=""
output+="===========================\n"
output+=" User Details \n"
output+="===========================\n"
output+="Full Name : $1\n"
output+="Phone Number : $2\n"
output+="Email Address : $3\n"
output+="===========================\n"
echo -e "$output"
When executed, it will:
- Declare a variable named
outputand initialize it with an empty string. - Use the
+=operator to concatenate formatted strings, including the first 3 positional arguments (i.e.$1,$2, and$3). - Output the value of the
outputvariable.
Which will produce this output:
$ ./script.sh 'John Doe' '362-4598-114' 'johndoe@mail.com'
===========================
User Details
===========================
Full Name : John Doe
Phone Number : 362-4598-114
Email Address : johndoe@mail.com
===========================
Manipulating substrings
In programming, a substring is a portion of a string.
Extracting a substring
To extract a substring, you can use the following syntax:
${variable:index:length}
Where:
variableis the name of the variable containing a string.indexis the position in the string of the first character of the substring.lengthis the number of characters to extract.
Note: In Bash, the first character of a string is located at index
0.
Example
Let's consider this script, that extracts and outputs information from a single string:
#!/bin/bash
input=$1
company=${input:0:4}
weight=${input:5:4}
price=${input:10:6}
output=""
output+="+---------+--------+--------+\n"
output+="| Company | Weight | Price |\n"
output+="+---------+--------+--------+\n"
output+="| ${company} | ${weight} | ${price} |\n"
output+="+---------+--------+--------+"
echo -e "$output"
When executed, it will:
- Declare a variable named
inputand initialize it with the value of the 1st positional argument. - Declare a variable named
companyand initialize it with a substring of theinputvariable going from index0to3. - Declare a variable named
weightand initialize it with a substring of theinputvariable going from index5to8. - Declare a variable named
priceand initialize it with a substring of theinputvariable going from index10to15. - Declare a variable named
outputand initialize it with an empty string. - Use the
+=operator to concatenate formatted strings, including the value of thecompany,weight, andpricevariables.
Which will produce this output:
$ ./script.sh 'AAPL 7.17 242.84'
+---------+--------+--------+
| Company | Weight | Price |
+---------+--------+--------+
| AAPL | 7.17 | 242.84 |
+---------+--------+--------+
Replacing substrings
To replace a substring with another substring, you can use the following syntax:
${string/substring/replacement}
Where:
substringis the string you want to replace.replacementis the string you want to replace it with.
Note: Forward slash characters
/in substrings need to be escaped using a backslash character\.
Example
Let's consider this script, that translates the abbreviations of a sentence into full words:
#!/bin/bash
sentence="In JS, using ES6+ features like async/await for handling I/O ops via APIs with REST can simplify DOM manipulation."
echo "[abbreviated] $sentence"
sentence="${sentence/JS/JavaScript}"
sentence="${sentence/ES6+/ECMAScript 6 and newer}"
sentence="${sentence/I\/O ops/input/output operations}"
sentence="${sentence/APIs/application programming interfaces}"
sentence="${sentence/REST/representational state transfer}"
sentence="${sentence/DOM/document object model}"
echo "[translated] $sentence"
When executed, it will:
- Declare a variable named
sentenceand initialize it with a string. - Output the original value of the
sentencevariable. - Replace various substrings in the
sentencevariable. - Output the updated value of the
sentencevariable.
Which will produce this output:
$ ./script.sh
[abbreviated] In JS, using ES6+ features like async/await for handling I/O ops via APIs with REST can simplify DOM manipulation.
[translated] In JavaScript, using ECMAScript 6 and newer features like async/await for handling input/output operations via application programming interfaces with representational state transfer can simplify document object model manipulation.
Outputting formatted strings
To output strings in a specific format using templates, you can use the printf command:
printf format [arguments...]
Where:
formatis a string that specifies the format of the output using specifiers, such as%cfor characters,%sfor strings,%dfor integers,%ffor floating-point numbers, etc.argumentsis a list of values inserted into theformatstring.
Notes:
To add whitespace padding to the left or right of a formatted value, you can use this syntax:
%[-]<padding><specifier>For example,
%-10sadds whitespace characters to the left of the string until the total length is 10 characters long.To specify the precision of a value (i.e. the number of decimals), you can use this syntax:
%.<precision><specifier>For example,
%.2fmeans that the number will have a maximum of 2 decimals.
Example
Let's consider this script, that outputs information about a fighter using templates:
#!/bin/bash
name="Georges St. Pierre"
surname="Rush"
height=5.10
weight=170
city="St. Isidore"
country="Canada"
wins=26
losses=2
printf "%s (\"%s\") is %.2f\" for %d lbs\n" "$name" "$surname" "$height" "$weight"
printf "He fight out of %s, %s\n" "$city" "$country"
printf "His record is %d wins and %d losses\n" "$wins" "$losses"
Which will produce this output:
$ ./script.sh
Georges St. Pierre ("Rush") is 5.10" for 170 lbs
He fight out of St. Isidore, Canada
His record is 26 wins and 2 losses
Summary
Here's a summary of what you've learned in this lesson:
- The
"$variable_A$variable_B"syntax is used to concatenate the value of multiple variables. - The
variable+=valuesyntax is used to append a value to the value of a variable. - The
${variable:index:length}syntax is used to extract a substring. - The
${string/substring/replacement}syntax is used to replace a substring. - The
printfcommand is used to output formatted strings.
Enjoying the courses?
I've made these courses completely free so anyone can learn from them. If they've helped you and you'd like to actively support the work behind BackendBrewery, you can leave a tip:
Support BackendBrewery