Programming newbie -help!!

Hi I am trying to learn shell script and i ran into an issue.

I am trying to read a file with few directories and tar them up.
I used a while loop but i end up overwriting tar file with only the last directory in the file being tared .

cat test.txt |
(
while read line
do
tar -czPf backup.tar.gz $line
done
)

If test.txt has test1, backup1, goo1

I end up having only goo1 in the tar

how do i get all 3 directories in the tar?

Thanks for your help in advance

That is useless use of cat..

Please see man pages for tar

tar -c is used to create new archieve.. try using tar -r
try

while read line
do
tar -rzPf backup.tar.gz $line
done<test.txt

Every time the loop runs, it creates the tar file in the same name (backup.tar.gz) thus over writing the previous one, hence it ends up only with the last tared file.
The tar command in your while loop should have variable for both source and destination.

Try this:

cat test.txt |
(
while read line
do
tar -czPf  backup_$line.tar.gz  $line
done
)

Hi Pamu,

I used -r but my understanding is it can used only if tar file already exists .. i am creating a new tar so it did not work

you can just create a empty tar file, then use that tar file in while loop

 
tar czPf backup.tar.gz --files-from /dev/null

You can create empty tar file as per itkamaraj's suggestion.

or add this to the command for checking presence of tar file:)

if [[ -f backup.tar.gz ]]
then
tar -rzPf backup.tar.gz file
else
tar -czPf backup.tar.gz file
fi

you guys are wonderful!! thank you very much .. it worked for me .. with while and the if condition ...

just an additional note .. -r says it cannot update compressed archive (ie .gz) So i only tared the file and at end of while loop , i gzip

while read file
do
if [[ -f backup.tar ]]
then
tar -rPf backup.tar file
else
tar -cPf backup.tar file
fi
done
gzip backup.tar
)

its ok for me just for learning .. but is there a better and more elegant way of doing it?

I think for creating tar using your above command you don't need to use if..:slight_smile:

You can directly use it. No need to check if it is present or not.

If you want to create .gz file what about using gzip (just thought:))