How To Bash Concatenate or Add Strings?
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
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
a=" to poftut"
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+=" to poftut"
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
to poftut .
printf -v c "$a to poftut"