24

I am trying to compress a folder with the tar command.

When I am trying to compress it, it works fine. The problem is with the file name.

Source path:

/data/file/

Destination path:

/data/repo/temp/file.tar.gz

tar zcvf $srcpath $destinationpath

I am executing the command from a different folder, and while extracting the folder I am getting all the sub directories instead of file folder alone.

Peter Mortensen
  • 933
  • 2
  • 11
  • 17
Seetha Raman
  • 255
  • 1
  • 2
  • 6
  • 1
    tar syntax is: `tar zcvf file.tar.gz /path/dir/to/compress` maybe you should change your command in `tar zcvf $destinationpath $srcpath` but it is unclear to me what you need. Could you elaborate your question with example of what you expect from tar command? – Lety Nov 24 '14 at 12:10
  • thanks for the comment, my problem is as following the comment that you shared here "tar zcvf file.tar.gz /path/dir/to/compres" this should works fine if we are in the same directory "file" my case is we are working from a different directory eg: /home/testuser1/file : file is the folder that i want to compress and am excuting the command from root not in home so we may need to give the whole path to the folder, while extrating am getting all the subdirectories from /home/testuser1/file instead of file folder – Seetha Raman Nov 24 '14 at 12:42
  • Probably a typo, but in your example, you mixed up source and destination. – Jacob Vlijm Nov 25 '14 at 08:13

1 Answers1

55

The easiest way to do that is to cd to the directory first:

cd /path/to/containing/folder && tar -zcvf tarfile.tar.gz foldername_tocompress

So that the (containing) folder's directory becomes the root directory of your compressed file.

A bit more advanced is using the -C option:

tar -zcvf tarfile.tar.gz -C /path/to/foldername_tocompress .

This creates a tar.gz file in the current (working) directory, containing all files/folders inside foldername_tocompress (mind the dot, saying all files/folders should be included).

Jacob Vlijm
  • 82,471
  • 12
  • 195
  • 299