Terminus by Warp
Bash Concatenate Strings

Bash Concatenate Strings

Prianka Subrahmanyam
Prianka Subrahmanyam
Software Engineer, Modern Treasury

Quick Reference

 $ X="String"
 $ X+="Concatenation" 
 $ echo $X
 
 # Output
 StringConcatenation

[#what-is-concatenation]What is Concatenation?[#what-is-concatenation]

Concatenation is the process of joining two strings together into one result. Some common use cases include creating a string containing multiple variables, and formatting messages containing user-defined inputs.

[#basic-concatenation]Basic Concatenation[#basic-concatenation]

In Bash, when variables or strings are written one after another, they automatically concatenate. In the following examples, the code will echo the same output to the terminal.

Concatenating variables:

 $ X="String"
 $ Y="Concatenation!"
 $ echo "${X}${Y}"
 
 # Output
 StringConcatenation!

Concatenating a variable and a string:

 $ X="String"
 $ echo "${X}Concatenation!"
 
 # Output
 StringConcatenation!

The curly braces are used to “protect” the names of the X and Y variables from other characters in the string. They make it clear to Bash that you are using a variable with a specific name. Use double quotes for strings containing variable names - this tells Bash to interpolate, or substitute in, the values of the variables.

[#mult-variable-types]Concatenation with multiple variable types[#mult-variable-types]

Bash infers the type of variables depending on how they are used. So, this means we can use integer or boolean variables in string concatenation as well.

Concatenating an integer and a string:

 $ X="The number four: "
 $ Y=4
 $ echo "$X$Y"
 
 # Output
 The number four: 4

Concatenating multiple numbers:

 $ X=314
 $ Y=159
 $ echo "$X$Y"
 
 # Output
 314159

[#using-addition-assignment-operator]Concatenation with += operator[#using-addition-assignment-operator]

You can use the += operator to append to the end of a string variable.

 $ X="Pi is the number "
 $ X+=3.14159
 $ X+= " and it is very handy."
 $ echo "$X"
 
 # Output
 Pi is the number 3.14159 and it is very handy.

Experience the power of Warp

  • Write with an IDE-style editor
  • Easily navigate through output
  • Save commands to reuse later
  • Ask Warp AI to explain or debug
  • Customize keybindings and launch configs
  • Pick from preloaded themes or design your own
brew install --cask warp
Copied!
Join the Windows waitlist:
Success! You will receive an email from Warp when the release is available to download.
Oops! Something went wrong while submitting the form.
Join the Linux waitlist:
Success! You will receive an email from Warp when the release is available to download.
Oops! Something went wrong while submitting the form.
Join the Linux waitlist or join the Windows waitlist
Join the Windows waitlist:
Success! You will receive an email from Warp when the release is available to download.
Oops! Something went wrong while submitting the form.