Compressing a folder (tar) without its containing directory in the folder name

117,660

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).

Share:
117,660

Related videos on Youtube

Seetha Raman
Author by

Seetha Raman

Updated on September 18, 2022

Comments

  • Seetha Raman
    Seetha Raman over 1 year

    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.

    • Lety
      Lety over 9 years
      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?
    • Seetha Raman
      Seetha Raman over 9 years
      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
    • Jacob Vlijm
      Jacob Vlijm over 9 years
      Probably a typo, but in your example, you mixed up source and destination.
  • David Duncan
    David Duncan about 8 years
    The dot at the end of your second command is going to include all files in the current directory...