Bash Concatenate Strings
Bash Concatenate Strings
In Bash scripting, concatenating strings is useful for various tasks where you need to combine multiple strings into a single string.
Syntax
string1="Hello"
string2="World"
result="$string1 $string2"
The basic syntax involves using double quotes and the $
symbol to concatenate strings.
Example Bash Concatenate Strings
Let's look at some examples of how to concatenate strings in Bash:
1. Concatenate Two Strings
This script concatenates two strings stored in the variables str1
and str2
and prints the result.
#!/bin/bash
str1="Hello"
str2="World"
result="$str1 $str2"
echo "$result"
In this script, the variables str1
and str2
are assigned the values 'Hello' and 'World', respectively. The result of concatenating these strings with a space in between is stored in the variable result
. The script then prints the concatenated string.
2. Concatenate Multiple Strings
This script concatenates three strings stored in the variables str1
, str2
, and str3
and prints the result.
#!/bin/bash
str1="Hello"
str2=","
str3="World!"
result="$str1$str2 $str3"
echo "$result"
In this script, the variables str1
, str2
, and str3
are assigned the values 'Hello', ',', and 'World!', respectively. The result of concatenating these strings with appropriate spaces is stored in the variable result
. The script then prints the concatenated string.
3. Concatenate Strings with User Input
This script prompts the user to enter two strings, concatenates them, and prints the result.
#!/bin/bash
read -p "Enter the first string: " str1
read -p "Enter the second string: " str2
result="$str1 $str2"
echo "The concatenated string is: '$result'"
In this script, the user is prompted to enter two strings, which are stored in the variables str1
and str2
. The result of concatenating these strings with a space in between is stored in the variable result
. The script then prints the concatenated string.
Conclusion
Concatenating strings in Bash is a fundamental task for combining multiple strings into a single string in shell scripting. Understanding how to concatenate strings can help you manage and manipulate strings effectively in your scripts.