Uncompress tar to specific directory + Other tar/untar tricks

There is a ‘-C’ option allow you to do this. However, it can fail in some situation. There are also some posts online that report this option does not work. If you have that problem, maybe you could try the solution here.

Here is my experience, on Cygwin (I didn’t test this on other systems)

1. If I type “tar -xzvf any.tgz –wildcards ‘*.log’ -C target_path “, the -C option is ignored and the files are unpacked to the current working directory. That is if there is some option before the -C option, it fails. No idea about the cause.

2. If I type “tar -xzvf any.tgz -C target_path –wildcards ‘*.log’ “, i.e. make -C the first option after the compressed file name, it works as expected.

Other people suggest the problem can also be resolved by command piping, something like “gzip -d any.tgz| tar xf – -C target_path”. You can try it too, although I don’t think this is the problem.


The following are some other tricks about tar:

1. tar/untar files/folders into/from a tar file. In order to include or exclude files during the tar ball creation or extraction, you may want to have a control of the files. You could use wildcards as shown above. Or prepare a file that contains a list of file path to be compressed or extracted. However, tar behaves weird if you mix the directory names and the file names in one file. The following is confirmed with tar v1.20 on Debian lenny. I used “tar xf test.tar –files-from=list.txt” to extract some files from test.tar, where list.txt contains a list of file paths. The file paths are generated using “tar tf test.tar”, so I’m sure the path names are exactly the same as stored in the tarball. I can manually delete some paths in list.txt and leave only the files I need there. However, I found if list.txt contains both directory names (which are ended with a ‘/’) and file names (without trailing ‘/’), that command fails! It gives some error information like ‘*** not found in the archive’. What? Not found. I’m sure the files are in there! After some trials and errors, I figured out I cannot mix the folder names with the file names. This is not documented as far as I know! e.g. in the list.txt if we have

./test/
./test/f1.txt

, this will cause the problem. But if I remove the line for the directory name, i.e. list.txt becomes

./test/f1.txt

, then the problem is gone.
This test tells us the ‘–files-from’ or ‘-T’ option of tar command is really designed for FILE names not for DIRECTORY names. The folders needed for files are created automatically.
This finding is very useful if you want to INCLUDE some files EXPLICITLY in the tar operations without using pattern. Pattern matching is always possible for file inclusion and exclusion though.

Share this:
Facebook Linkedin Twitter Digg Email

Leave a Reply