tar command in for loop

I know it is the basic question but please do help me. I compressed and archived my server log file using tar command

for i in server.log.2016-07-05 server.log.2016-07-06 ; do tar -zcvf  server2.tar.gz $i; done

the output of the above loop is

server.log.2016-07-05
server.log.2016-07-06

But while listing the file using tar -tvf server2.tar.gz the output obtained is

rw-r--r-- root/root 663643914 2016-07-06 23:59 server.log.2016-07-06

i.e., I archived two files but only one file was displayed which means archive doesn’t have both files, archive must have all the files. Please help on this.

I just tested with these two files but my folder has multiple files.Since I didnt get expected output I was not proceeded with all the files in my folder.The exact loop I am going to use is

Previousmonth=$(date "+%b" --date '1 month ago')

for i in $(ls -l | awk '/'$Previousmonth'/ && /server.log./ {print $NF}');do;tar -zcvf server2.tar.gz $i;done

Answer

Each time the loop is executed, the command tar is executed to put one file to the file server2.tar.gz. The file will end having only one file.

Either use tar option to append files:

tar --append -zcvf server2.tar.gz "$i"

or just give the list of file to tar (please don’t use this command):

tar -zcvf server2.tar.gz  $(ls -l|awk '/'$Previousmonth'/&&/server.log./{print $NF}')

However, that command line has some issues:

  • parsing ls output (wrong).
  • using $Previousmonth un-quoted (wrong).
  • building a list of files that may have embedded spaces (in-reliable).

use this (pair of) command(s) instead:

month=$(date "+%Y-%m-" --date '1 month ago')
find ./ -name "server.log.${month}*" -exec tar -zcvf server2.tar.gz '{}' +

Leave a Reply

Your email address will not be published. Required fields are marked *