Shell Script to Concatenate Two Strings
Brief: This example will help you to concatenate two or more strings variable in a bash script. This tutorial helps you with multiple shell script examples of concatenating strings in a shell script.
The first example is a general way to concatenate variables of string. You can simply write all the variable one after another:
1 2 3 4 5 6 7 8 9 | #!/bin/bash # Shell program to concatenate two strings in variable str1="Welcome " str2="TecAdmin!" str3=$str1$str2 echo $str3 |
Output:
Welcome TecAdmin!
Another Example
You can also use +=
operator to concatenate two strings and store results in the first string.
1 2 3 4 5 6 7 8 | #!/bin/bash str1="Welcome " str2="TecAdmin!" str1+=$str2 echo $str1 |
Output:
Welcome TecAdmin!
One More Example
Use another example with one string variable with user input and another fixed strings.
1 2 3 4 5 6 | #!/bin/bash # Shell program to concatenate two strings read -p "Enter your name: " name echo "Welcome $str1" |
Script execution result:
Enter your name: Rahul Welcome Rahul
Using {} with Variables
In some situation, you may face issue while concatenating one string with another string variable as shown in below example. Here you need to use curly braces around variable name.
1 2 3 4 5 6 7 | #!/bin/bash filename="backup" echo "$filename_03132018.sql" ### This will not work echo "${filename}_03132018.sql" ### Correct |
Output
.sql backup_03132018.sql
You can see that first output if incorrect and second output is correct using {}
around variable name.