1

I have 3 lines in file /root/backuplist.txt.

The first echo prints perfectly, but the last one prints an empty line; I'm not sure why. Somehow, the $DIRS value is getting unset.

#!/bin/bash

cat /root/backuplist.txt |
while read line
do
  DIRS+="$line "
  echo $DIRS
done

echo $DIRS
mklement0
  • 382,024
  • 64
  • 607
  • 775

1 Answers1

3

Problem is use of pipe here, which is forking a sub-shell for your while loop and thus changes to DIRS are being made in the child shell that are not visible in the parent shell. Besides cat is unnecessary here.

Have it this way:

#!/bin/bash

while read -r line
do
   DIRS+="$line "
   echo "$DIRS"
done < /root/backuplist.txt

echo "$DIRS"
anubhava
  • 761,203
  • 64
  • 569
  • 643