0

I have a folder with files which I want to zip into a tar.gz file. I am using the following command:

tar -czvf filename.tar.gz  foldername

Sure enough this creates the file filename.tar.gz. However, when I unzip the tar file, by default it creates a folder filename and places all the files into the folder.

Can I avoid this folder creation when I create the tar file itself. I tried the following command but it doesn't work.

tar -czv filename.tar.gz  foldername

I am using Ubuntu 14.04.

My current directory structure is as follows:

~/Test/foldername

The directory foldername has all the files that I want to zip. My codes are as follows:

cd Test
tar czvf filename.tar foldername/*
  • You can always cd before zipping – Weijun Zhou Jan 15 '18 at 7:12
2

Another way is to utilize the -C command line argument, as in the following:

tar czvf filename.tar.gz -C foldername .

Note the final ., which tells tar to include "this directory" after having cd-ed into foldername by virtue of the -C foldername argument.

You end up with names in the tar file starting with ./ instead of foldername/, and they thus unpack into the current working directory.

If on the other hand, you have a tar file with names like foldername/X, and you want to un-tar that without the first directory component, then the argument --strip-components=1 is your friend. Thus, the untar command might be:

tar xzf filename.tar.gz --strip-components=1

By that argument, the first directory component of all path names are "stripped away" during the un-tar-ing. Check out man tar for all the details.

  • Ronnquist Thank you. however, my question is about avoiding the folder that gets created when you unzip the tar file. Can I avoid that and unpack the files directly into the directory. – popeye Jan 15 '18 at 7:20
  • Or, alternatively, cd into the directory and run tar cvzf ../filename.tar.gz .. – Johan Myréen Jan 15 '18 at 7:22
  • @popeye, yes; that's exactly what happens. The very same as what Johan suggests, but with only the tar program doing the cd (not the whole shell) – Ralph Rönnquist Jan 15 '18 at 7:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.