In this tutorial, learn different ways to append string variables

There are multiple ways to check if a string contains a substring

Simple variable append

Declare two string variables in bash script printed to console using echo by appending(enclosed in a double quote with variable syntax)

string1="Hello, "
string2='Welcome to w3schools.'
echo "$string1 $string2 "

You can also append without double quote

echo $string1 $string2

Output:

Hello, Welcome to w3schools.

Another example, to concatenate a string to the same variable and print to console

result="My site is"
result="${result} w3schools"
echo "${result}"

Output:

My site is w3schools

Append strings using shorthand arithmetic operator

shorthand arithmetic operator(+=) is used in numbers to add value to the variable and save the result to the variable.

This can also be used for strings for append string to a variable.

For example,

  • a+=1 is equal to a=a+1 in case of numbers
  • str+=“test” will becomes str=str+“test” in case of strings

Output:

One Two three

Substring checks using grep command

grep command search for a given string and piped to main string to compare it

mainstring='Welcome to w3schools'

if echo "$mainstring" | grep -q "w3schools"; then
  echo "w3schools exists in main string"
fi