• Uncategorized

About java : How-to-create-tar-file-which-contains-only-file

Question Detail

I have a file in /tmp/a.crt I will have to make a.tgz which contains a.crt not tmp/a.crt. As i am running tar command through java I can’t navigate to /tmp and execute tar -cvf a.tgz a.crt
If i run tar -cvf a.tgz /tmp/a.crt it creates a a.tgz which contains tmp/a.crt .

I tried tar --exclude='/tmp' -cvf a.tgz /tmp/a.crt but while untaring it says

gzip: stdin: not in gzip format

tar: Child returned status 1

Is there any way to achieve my requirement.

Question Answer

If you want to create a compressed tar file (.tgz or .tar.gz), you have to use the option z. Otherwise you have only an uncompressed tar file (.tar). You probably omitted this option during creation.

Here is a Bash session demonstrating what you want (as I understand it):

# first, create test files
$ mkdir tmp
$ touch tmp/a.crt
$ find .

# use "-C" to keep the filename out of the archive
$ tar -C tmp -czvf a.tgz a.crt

# confirm results
$ tar tf a.tgz 

As you can see, in the final a.tgz file, there is no tmp/ directory present.

This is generally a bad idea, creating what is sometimes called a “tar bomb” (link). But presumably you have a good reason for it (:

You may also like...

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.