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

Updated:   |  Bash (Scripting) articles

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 at 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. In this example, IFS split as new lines.

#!/bin/bash
IFS=$'\n'

out="line one"$'\n'
out+="line two"$'\n'
out+="line three"$'\n'

for line in $out; do
  echo "[$(date '+%m-%d-%Y %H:%M:%S')] $line"
done

unset IFS

 

Now the script should output each line, split a new lines.

~]$ bash testing.sh
[10-24-2024 01:34:37] line one
[10-24-2024 01:34:37] line two
[10-24-2024 01:34:37] line three

 

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


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