Recent Changes - Search:

Basics

Languages

Tools

OS

Resources

PmWiki

pmwiki.org

edit SideBar

StringConcatenation

Concatenating strings is relatively straightforward in Bash, as opposed to doing arithmetic.

Concatenation occurs naturally, just by putting strings next to each others and can also be done with variables. In order to define strings with spaces, the string must be bracketed by single quotes ('). This is especially useful to add leading or trailing spaces to properly interact with variables. Although it is not necessary for single words, it can save you trouble to use single quotes there as well.

Appending a variable to a string

pet=cat
sentence='I have a nice '$pet
echo $sentence
-> I have a nice cat

Appending a string to a variable

season=Winter
sentence=$season' is cold'
echo $sentence
-> Winter is cold

Mixing it up

season=winter
adj=cold
sentence='It is '$adj' in the '$season' here.'
echo $sentence
-> It is cold in the winter here.

Complications

Appending single words to variables can be a bit trickier and is one reason why using the single quotes is recommended.

season=winter
adj=$seasony
echo $adj
->
adj=$season'y'
echo $adj
-> wintery

The first result is obtained because it tries to assign the content of a variable called "seasony" to adj, but since the seasony variable does not exist, adj gets assigned nothing as its content. By opposition, the second try takes the content of "season" and adds 'y' to it, making wintery.

Edit - History - Print - Recent Changes - Search
Page last modified on July 31, 2015, at 04:56 PM