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:

  1. Define a variable named directory and initialize it with the value of the HOME environment variable concatenated to the "/scripts" string.
  2. Define a variable named file and initialize it with the string "reflect.sh".
  3. Define a variable named path and initialize it with the concatenated values of the directory and file variables.
  4. Output the content of the file located at the path contained in the path variable using the cat command.

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:

  1. Declare a variable named output and initialize it with an empty string.
  2. Use the += operator to concatenate formatted strings, including the first 3 positional arguments (i.e. $1, $2, and $3).
  3. Output the value of the output variable.

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:

  • variable is the name of the variable containing a string.
  • index is the position in the string of the first character of the substring.
  • length is 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:

  1. Declare a variable named input and initialize it with the value of the 1st positional argument.
  2. Declare a variable named company and initialize it with a substring of the input variable going from index 0 to 3.
  3. Declare a variable named weight and initialize it with a substring of the input variable going from index 5 to 8.
  4. Declare a variable named price and initialize it with a substring of the input variable going from index 10 to 15.
  5. Declare a variable named output and initialize it with an empty string.
  6. Use the += operator to concatenate formatted strings, including the value of the company, weight, and price variables.

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:

  • substring is the string you want to replace.
  • replacement is 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:

  1. Declare a variable named sentence and initialize it with a string.
  2. Output the original value of the sentence variable.
  3. Replace various substrings in the sentence variable.
  4. Output the updated value of the sentence variable.

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:

  • format is a string that specifies the format of the output using specifiers, such as %c for characters, %s for strings, %d for integers, %f for floating-point numbers, etc.
  • arguments is a list of values inserted into the format string.

Notes:

  • To add whitespace padding to the left or right of a formatted value, you can use this syntax:

    %[-]<padding><specifier>
    

    For example, %-10s adds 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, %.2f means 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+=value syntax 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 printf command 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
Working With Strings in Bash | Backend Brewery