Bash concatenate strings

Concatenating in bash programming is the operation of joining character strings end to end. Adding two strings in bash to one another and getting both the strings in the output is useful in day-to-day tasks or within bash scripts.

In this tutorial we’ll answer how to concatenate strings in bash, along with some common questions and examples.

Table of Contents

  1. How to concatenate strings in bash?
  2. How to concatenate strings and numbers bash?
    1. Bash script concatenation with a for loop

How to concatenate strings in bash?

Given the variable names of VARIABLE_NAME1 and VARIABLE_NAME2, to print them both out in the terminal it would be:

VARIABLE_STRING1="foo"
VARIABLE_STRING2="bar"

echo $VARIABLE_STRING1 $VARIABLE_STRING2
# Output
foo bar

Using a dynamic bash variable with literal strings

VARIABLE_STRING1="foo"
VARIABLE_STRING2="bar"

VARIABLE_STRING3=${VARIABLE_STRING1}${VARIABLE_STRING2}

# Print results
echo $VARIABLE_STRING3
# Output
foobar

Or a shorter way to do it with the += shorthand concatenation operator. Effectively a+=b is the same as a=a+b.

VAR1="Hello "
VAR2="World!"

VAR1+=$VAR2

# Print the result string
echo $VAR1
# Output
Hello World!

How to concatenate strings and numbers bash?

Example being if we have a bash variable that is a string and another one that is a number, those are still treated in the same way.

STRING="foo"
NUMBER=2

# Print results
echo $STRING $NUMBER
# Output
foo 2

Bash script concatenation with a for loop

Example to use a for loop over an array of strings then echo the results:

  • The echo -n is to not output the trailing newline.
  • for i in "one" "two" "three" "four" "five"
    do 
      echo -n $i
    done
    # Output
    onetwothreefourfive