Kallaste
Kallaste

Reputation: 767

Bash, error storing a directory name in a variable

I know this is probably a silly question, but I am trying to write my first bash script and am having some trouble. It is a backup script that reads a text file to get a list of directories to back up, then stores them in a variable so it can use the variable value as input for the tar command. But when if I store the value /home in the backupdirs text file, it gives me an error saying /home is a directory, and it does not store it in the variable. Can I not store a directory name in a variable like this? How do I get around it?

#!/bin/bash

BACKUP_DIRS=

cat /root/backupdirs.txt |
{
        while read line
        do
            echo $line
            BACKUP_DIRS=$BACKUP_DIRS $line
        done
}

echo $INPUT_DIRS

/bin/tar -czf backup $BACKUP_DIRS

Upvotes: 1

Views: 327

Answers (1)

Zombo
Zombo

Reputation: 1

Once you use the pipe, it creates a subshell. Then BACKUP_DIRS is saved in the subshell. Once the subshell exits, the variable is destroyed along with it. One way around this, do it without a pipe

while read line
do
  echo $line
  BACKUP_DIRS+=" $line"
done </root/backupdirs.txt

Upvotes: 1

Related Questions