Bash (Scripting) - append values to a variable (+=)

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

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.





Please enter f047c in the box below so that we can be sure you are a human.




Comments

Web design by yours truely - me, myself, and I   |   jeremy.canfield@freekb.net   |