Open In App

Shell Script to Concatenate Two Strings

Improve
Improve
Like Article
Like
Save
Share
Report

String concatenation is the process of appending a string to the end of another string. This can be done with shell scripting using two methods: using the += operator, or simply writing strings one after the other. The examples below show some shell scripts that can be used to concatenate strings.

Example 1:

In this example, we will concatenate two strings using += operator. The input strings will be stored in two variables, a and b.

Code:

#Read inputs a and b and store string variables in them.
read a b

#append b to the string a
a+=$b

#Output the resulting string
echo $a

Example 2:

In this example.  We will concatenate multiple variables using the += operator in a for loop, where every two strings are separated by a space.

Code:

#create an empty string c
c=""

#read input strings and store them in a and b
read a b

#for loop to append a group of strings to the variable c.  
for val in $a 'ipsum' $b 'sit amet' 10
do
 c+="$val "
done

#The result is a string that consists of all the elements concatenated into a single string
echo "$c"

Notice that the integer 10 inside the array was treated the same as the strings. This is because in shell scripts, variables are treated depending on context and not segregated by type.

Example 3:

In this example, we have two variables a and b, and we stored a string in each variable. We want to concatenate them one after the other. The result of concatenation will be stored in the variable c.

Code:

#Read inputs a and b and store string variables in them.
read a b

#concatenate the strings by writing one after the other. Store the result in c
c=$a$b

#output c
echo $c

We can also add extra text elements by simply inserting the text surrounded by double quotations “”.  In this case we added a space between the two strings, a hyphen before them, and an exclamation point after. An alternative method would be to surround the entire text with double quotations ” ” and surround variable names by curly brackets {} so that the other elements in the string do not interfere with them.

Code:

#Read inputs a and b and store string variables in them.
read a b

#concatenate the strings by putting one after the other. Store the result in c
c="-"$a" "$b"!"

#alternative solution:
#c="-${a} {b}!"

#output c
echo $c

Example 4:

This is another example that shows how to concatenate strings by writing them one after the other. In this case we have 4 strings, two of them are stored in variables a and b.

Code:

#Read inputs a and b and store string variables in them.
read a b

#concatenate the strings by putting one after the other
echo $a" ipsum "$b" sit amet"


Last Updated : 28 Mar, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads