Using Bash to Concatenate Strings

Bash scripting makes concatenating strings simple and fun. All the normal Bash features are available and more complex approaches can be applied with looping, splitting text into arrays, and even specifying custom IFS values!
bash concatenate strings alpharithms

Bash is a shell programming language designed to provide developers a means to write quick-and-dirty scripts to automate repetitive tasks. It integrates with Linux/Unix tools like grep, cat, and more but also provides language tools like loops and the means to manipulate stings — including string concatenation.

Using bash to concatenate strings is almost eerily simple compared to other full-fledged programming languages like Java, C, or Rust. Where programming languages often require clunky syntax, the use of string formatting models, or even the indexing into arrays — concatenating strings in bash is a very familiar experience. Let’s take a look.

Basic Bash String Concatenation

Bash essentially allows developers to define string variables and then use them together as though they were words in a text. Consider the following bash script:

#!/bin/bash

# define some variables
STRING1="hello"
STRING2=","
STRING3="world"
STRING4="!"

# concatenate strings
echo "$STRING1$STRING2$STRING3$STRING4"

Here we see 4 variables defined, each of which is initialized with a string value. At the bottom of this script, the echo command is used to send the value of all these variables — back to back without separation — to stdout. The output is as follows:

$ ./script.sh

hello,world!

Note: the $ ./script.sh is just indicating this script was run from the command line. The actual output is just hello,world! printed to the console (stdout).

As an alternative approach, we could have assigned the $STRING[1-4] variables to another variable and used the echo command to send that value to stdout. Consider the following code:

#!/bin/bash

# define some variables
STRING1="hello"
STRING2=","
STRING3="world"
STRING4="!"

# Define a combination of strings
STRING5="$STRING1$STRING2$STRING3$STRING4"

# concatenate strings
echo "$STRING5"

The output of this script is as follows:

$ ./script.sh

hello,world!

Identical — hinting at the differences in these methods being primarily that of preference. The first method is suitable in cases where the value is to be used once. The latter approach will make the reuse of the concatenated strings more accessible and reduce redundant code. As a final example, let us consider adding additional text to the output that hasn’t been defined as a variable:

#!/bin/bash

# define some variables
STRING1="hello"
STRING2=","
STRING3="world"
STRING4="!"

# Define a combination of strings
STRING5="$STRING1$STRING2 lovely $STRING3$STRING4"

# concatenate strings
echo "$STRING5"

Here we’ve inserted into our string a single space, followed by the character sequence lovely followed by another single space. The output of this updated script is as follows:

$ ./script.sh

hello, lovely world!

Here we see that bash accommodates on-the-fly string concatenation such that developers can mix both variable strings and string literals. This looks like hot garbage coming from many formal programming languages but makes bash well suited for quick-and-dirty scripting. Now let’s consider concatenating user input — spoiler, it’s basically the same thing.

Using Bash to Concatenate Strings from User Input

Getting user input in Bash is a topic for another day. Here we’ll assume some level of knowledge in gathering user input. The following script prompts a user for exactly three words (and assumes the user will enter them without issue) and then concatenates these string values into a reply message:

#!/bin/bash

# prompt user for 3 words
read -p "Enter 3 words: " w1 w2 w3

# echo to stdout
echo "Your words are: $w1, $w2, and $w3."

This uses the read tool along with the -p flag to prompt the user for input and then save that input in three variables: $w1, $w2, $w3. With these variable values, the script then uses the echo tool to send their values concatenated in a more human-friendly format to stdout. The result is as follows:

$ ./script.sh
Enter 3 words: dog fish cat

Your words are: dog, fish, and cat.

The first line is the command that runs the script, the second line is the prompt, followed by three words entered by a user: dog, fish, and cat. Finally, a human-friendly form of these variables is echoed in the terminal window (stdout). These first two approaches are great for pre-defined texts or even user texts. Now let us consider how one might deal with a lot of text.

Using Bash to Concatenate Strings in a Loop

Concatenating strings in a loop can be useful for a range of applications. One might have texts from multiple sources, large amounts of text, or need to run some filtering logic, or maybe even find the need for some sequential labeling of data.

For Loop String Concatenation

In any case, using for loops and while loops can be useful helpers in concatenating strings. Fortunately, Bash makes either option easy. Let us first consider an example of using a for loop in bash to concatenate strings:

#!/bin/bash

# define a sentence
text="The only investors that don’t need to diversify are those that are right 100% of the time."

# define unwanted words
stopwords=("the" 'THAT' 'to' 'ARE' 'those' 'of')

# define output with initiali value of the empty string
output=''

# for each word in the text, check if it is wanted.
for word in $text; do

  # if the lowercase version of word is NOT found in an
  # array of the lowercase versions of each word
  # in the stopwords array, add it to the output
  if ! [[ "${stopwords[*],,}" =~ ${word,,} ]]; then

    # concatenate the word to the existing output
    # with a trailing space.
    output="${output}${word} "
  fi
done

# send the final output to stdout
echo "Output: $output"

In this short script the following sequence of actions happens:

  1. A string of text is defined as our source.
  2. An array of unwanted words (stopwords) has been defined.
  3. A for loop is used to loop over each word in the sentence.
  4. An if statement is used to determine if a word is NOT in the stopwords array.
  5. The output variable is re-defined as its previous form concatenated with the new qualified word, with an ending space for readability.

Finally, the end of this Bash script uses the echo tool to send the resulting output variable to stdout where it is displayed in the terminal window as follows:

$ ./script.sh

Output: only investors don’t need diversify right 100% time. 

Here we see that any words not found in the stopwords array (case insensitive matching) has been added to the final output. This is an example of how using a for loop in Bash for string concatenation can be a useful approach — one used for filtering unwanted words from a large body of text in this case.

While Loop String Concatenation

A while loop is often desired in cases where a clear termination condition is present. Bash’s for loops are really more akin to the foreach concept of taking an action for every item in a collection whereas the while loop is more akin to repeating an action until a condition is reached. Let’s consider a simple bash script to use a while loop to only extract the first 10 non-whitespace characters of our text:

# define a sentence
text="The only investors that don’t need to diversify are those that are right 100% of the time."

# creates an array of text
text_array=($text)

# init an output variable and counter
output=''
count=1

# get words until
while [[ $count -lt 11 ]]; do

  # re-define output as previous with next
  # word concatenated.
  output="$output($count)${text_array[$count]} "

  # C-Style incrementation of count variable
  ((count++))
done

# echo the resulting output to stdout
echo "$output"

Here we see the following sequence of actions executed:

  1. Define a string of text.
  2. Split that string into an array of words.
  3. Initialize a count variable with a value of 1.
  4. Loop through the array until our count reaches 11 (10 total)
  5. Add the next member of the text_array to the output string, prefixed with a (count) value indicating the number of that addition.
  6. Increment the count variable using C-style syntax.

The output from this script is as follows:

$ ./script.sh

(1)only (2)investors (3)that (4)don’t (5)need (6)to (7)diversify (8)are (9)those (10)that

Here we see only the first 10 words of our text displayed in the terminal window, as expected.

Note: IntelliJ-based IDEs will nag about the text_array=($text) syntax. To eliminate the nag just add # shellcheck disable=SC2206 above the line.

Final Thoughts

Using Bash string concatenation is a convenient means of handling short-order scripting needs. It lacks the robustness of formal programming languages but offers the trade-off of simplified syntax. Using Bash along with other *nix tools like read, cat, and cut can make even shorter order of concatenating strings.

Here we’ve seen Bash applied to string concatenation in an explicit case, a for loop, a while loop, and even via getting user input. These approaches are not meant to illustrate an exhaustive selection of ways to concatenate strings using Bash scripting — rather just intended to be the seeds of inspiration.

Zαck West
Full-Stack Software Engineer with 10+ years of experience. Expertise in developing distributed systems, implementing object-oriented models with a focus on semantic clarity, driving development with TDD, enhancing interfaces through thoughtful visual design, and developing deep learning agents.