Thursday, February 21, 2013

tar creation with option C and effect of globbing



There was a need to archive some logs for investigation...
Without much thought, I fire this command and there it was..bummer!!


[root@mysys rmlater]# tar -zcvf /var/tmp/test.tgz -C /root/myapp/log/ 
appProc.log.*
tar: appProc.log.*: Cannot stat: No such file or directory
tar: Error exit delayed from previous errors


[root@mysys rmlater]# ll /root/myapp/log/appProc.log.*
-rw-r--r-- 1 root root 338928 Feb 22 10:47 /root/myapp/log/appProc.log.0
-rw-r--r-- 1 root root 460000 Feb 20 22:40 /root/myapp/log/appProc.log.1
-rw-r--r-- 1 root root 460000 Feb 18 21:39 /root/myapp/log/appProc.log.2
-rw-r--r-- 1 root root 462685 Feb 16 20:38 /root/myapp/log/appProc.log.3
-rw-r--r-- 1 root root 907643 Feb 14 20:29 /root/myapp/log/appProc.log.4

[root@mysys rmlater]# pwd
/var/tmp/rmlater

Solution 1:
tar -zcvf /var/tmp/test.tgz /root/myapp/log/appProc.log.*

Solution 2:
cd /root/myapp/log/; tar -zcvf /var/tmp/test.tgz appProc.log.*

Difference between Solution 1 and Solution 2:
1) The files are archived in package structure opt/cpf/oma/esymacstarter/. You will see the 

appProc.log.* under opt/cpf/oma/esymacstarter/ when you extract the test.tgz

2) The files are archived into test.tgz without any package structure

Now looking at the error:
tar: appProc.log.*: Cannot stat: No such file or directory

tar -C option => Instructs tar to change the working directory and perform archiving

Reason why it failed: Due to the wildcard pattern and how it is interpreted by shell
Shell expands the files into matching files as per the wild card pattern. This operation is 
called "globbing"...

When shell does globbing, it does so from the current working directory - It checks for 
files matching "appProc.log.*" in /var/tmp/rmlater

[root@mysys rmlater]# ll
total 0
-rw-r----- 1 root root 0 Feb 22 11:25 opt


No files matching appProc.log.* => Cannot stat: No such file or directory

Why use -C option then:

It comes handy when when you want to go to multiple directories and archive different files from them. Most importantly, when you want to put them into one tgz file!!

One use case I can think of is collecting logs for different SW modules from more than one 
folder. In case you want to explore tar options in detail, check out this excellent resource GNU tar manual

No comments:

Post a Comment