Concatenate Strings in Bash Script

Concatenate Strings in Bash Script
Concatenate Strings in Bash Script

Concatenate Strings in Bash

Concatenating Strings in Bash Script is one of the easiest operations. Concatenating string means appending one string to another and creating a new string. This string joining operation used more often in Bash Script. In this tutorial, you are going to learn to concatenate Strings in Bash Script.

Concatenate Strings

The easiest way for concatenating strings is writing variables side by side and the returned string will be the concatenated string.

In below example we are concatenating STR1 with STR2 by writing these two variables side by side:

STR1="Welcome to "
STR2="Linux4one"
RESULT="$STR1$STR2"
echo "$RESULT"

The output should look like:

Welcome to Linux4one

Another Example for concatenating strings with the number as value is given below:

STR1="Linux"
STR2="4"
STR3="one"
RESULT="$STR1$STR2$STR3"
echo "$RESULT"

The output should look like:

Linux4one

Concatenate Variables with Literal

You can also concatenate variables with literal string by using curly braces in following way.

In below example curly braces are used so the variable should not mix up with literal string:

STR1="Linux4"
RESULT="${STR1}one"
echo "$RESULT"

The output should look like:

Linux4one

Bash Concatenate Strings with Underscore

Concatenate String with Underscore in one of the more used tasks in scripting. Whenever we want to give the name to the file we may use underscore or hyphen for imploding words.

In below example two strings are concatenated with an underscore:

VAR1="BASH"
VAR2="SCRIPT"
echo "${VAR1}_${VAR2}"

The output should look like:

BASH_SCRIPT

Concatenate Strings with + Operator

Like in Java Programming language, you can concatenate strings by using + operator. Concatenating strings by using + operator is one of the best ways to concatenate strings.

In the following example we are going to concatenate strings with += operator:

VAR1="BASH"
VAR1+=" SCRIPT"
echo "$VAR1"

The output should look like:

BASH SCRIPT

Bash Concatenate Strings in Loop

Following is an example for concatenating strings in a loop:

n=4
result=""
for i in $(seq 0 $(($n > 0? $n-1: 0))); do 
  result+="rank-$i"
  result+=" "
done
echo $result

The output should be:

rank-0 rank-1 rank-2 rank-3

Conclusion

You have successfully learned Concatenate Strings in Bash Script using different methods. If you have any queries regarding this tutorial please don’t forget to comment out.

LEAVE A REPLY

Please enter your comment!
Please enter your name here