Bash provides string operations. We can use different operations like remove, find or concatenate strings in bash. In this tutorial we will look how to add or concatenate strings in Linux bash.
Put Variables Side By Side
The simplest and easy to understand way to concatenate string is writing the variables side by side. We will write the variables like $a$b . We do not need extra operater or function to use. In this example we will concatenate two variables named $a
and $b
into $c
.
a="This is" b="poftut.com website" c=$a$b echo $c

Double Quotes
Other useful alternative is using string variables inside strings which is defined with double quotes. We will put the variables name into double quotes with soe string. In this example we will put variable name $a
into string Welcome
a=" to poftut" c="Welcome $a" echo $c

Append Operator
Popular programming languages provides +=
compact add operator which is consist of plus and equal sign. We can add existing variable new string. This will add new string to the end of string variable. In this example variable named $a
has all ready string value Welcome
and we will add to poftut
like below.
a="Welcome" a+=" to poftut" echo $a

Printf Function
printf
is a function used to print and concatenate strings in bash. We can provide the string we want to print into a variable. We will use -v
option with the variable name and the string we want to add. In this example we will use string variable $a
and to poftut
.
a="Welcome" printf -v c "$a to poftut" echo $c
