Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

variable
bash
communitycreator
string

How to concatenate string variables in Bash

Gutha Vamsi Krishna

Overview

We can concatenate string variables by using bash in the following two ways: 

  1. Writing them one after the other
  2. Using the += operator

Syntax

#first way
var_name = "${string variable name} provide string here"

#second way
variabe_name+="provide string here"
  • The first way is useful when we want to concatenate the string and store it in a different variable.
  • The second way is useful when we want to concatenate the string and store it in the same variable.

Example

# given string
str1="Hello"

#concatenate using first way
str2="${str1} World"
echo $str2

#concatenate using second way
str1+=" World"
echo $str1

Explanation

  • Line 2: We declare and initialize the first string variable, str1.
  • Line 5: We declare the second string variable, str2, and initialize it by concatenating the first way.
  • Line 9: We concatenate the string to the same variable using the += operator and store it in the same variable.

RELATED TAGS

variable
bash
communitycreator
string
RELATED COURSES

View all Courses

Keep Exploring