Let's say the fruit variable contains the following.
fruit="apple banana orange grape"
The += operator can be used to append values to the end of the variable. In this example, pineapple is appended to the end of the fruit variable. Notice the single white space, so there there is a space between grape and pineapple.
#!/bin/bash
fruit="apple banana orange grape"
fruit+=" pineapple"
echo $fruit
Running this script should return the following.
~]$ bash testing.sh
apple banana orange grape pineapple
Splitting a new lines
However, let's consider the following. Let's say you want to print each line.
#!/bin/bash
out="some long line of text"
out+=" the next long line of text"
for line in $out; do
echo $line
done
The following script will split each element at whitespace.
~]$ bash testing.sh
some
long
line
of
text
the
next
long
line
of
text
To split at new lines, you will need to set the IFS variable at the beginning of your script to separate fields at new lines and also use out+=$'\nyour text here' when appending lines to the "out" variable.
#!/bin/bash
IFS=$'\n'
out="some long line of text"
out+=$'\nthe next long line of text'
for line in $out; do
echo $line
done
unset IFS
Now the script should output each line, split a new lines.
~]$ bash testing.sh
some long line of text
the next long line of text
Did you find this article helpful?
If so, consider buying me a coffee over at