karthikraj karthikraj - 1 year ago 59
Bash Question

Using '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:


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 doesnt have both files right?? Please help on this.

I just tested with these two files but my folder has multiple files. Since I didn't 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

I am trying to compress and archive multiple files but while listing the files using
tar -tvf
it doesn't shows all the files.

Answer Source

You don't need a loop here. Just list all the files you want to add as command line parameter:

tar -zcvf server2.tar.gz server.log.2016-07-05 server.log.2016-07-06

The same goes for your other example too:

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

Except that parsing the output of ls -l is awful and strongly not recommended.

But since the filenames to backup contain the month number, a much simpler and better solution is to get the year + month number using the date command, and then use shell globbing:

prefix=$(date +%Y-%m -d 'last month')
tar -zcvf server2.tar.gz server.log.$prefix-??
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download