Concatenate Variables to Strings in Bash
In Bash Scripting, variables can store data of different data types. Often it is required to append variables to strings or include them in a string while echoing some debug information to the screen.
In this tutorial, we shall learn to concatenate variables to Strings and also learn to include variables within a string while echoing.
Include variable in a String
A variable could be embedded in a string by using variable substitution using $ and variable name.
In the following example, we will take a value in a variable, and include this variable in a string using $ followed by variable name. The resulting string will have the value of variable in place of $variable.
Bash Script
#!/bin/bash
n1=10
echo "Number of Apples : $n1"
Output
Number of Apples : 10
Concatenate Two Variables using String
In the following example, we use the idea of including variables in a string to concatenate two variables.
Bash Script
#!/bin/bash
n1=10
str1="Number of Apples : "
str1="$str1$n1"
echo $str1
Output
Number of Apples : 10
Conclusion
In this Bash Tutorial, we learned how to concatenate variables to Strings in Bash.