Tar and compress a file in one step

Creating a compressed archive in UNIX in a single step is faster and is often the only method when disk space is limited.

To archive and compress a directory called ‘target’ in the current working directory into a file called target.tgz use:

tar cf - target | gzip -c > target.tgz

The – in the place of a tar output filename directs tar to send its output to the standard output which is redirected to gzip. Substituting bzip2, when available in your operating system, will also work and generally provides better compression ratios.


About Quinn McHenry

Quinn was one of the original co-founders of Tech-Recipes. He is currently crafting iOS applications as a senior developer at Small Planet Digital in Brooklyn, New York.
View more articles by Quinn McHenry

The Conversation

Follow the reactions below and share your own thoughts.

7 Responses to “Tar and compress a file in one step”

  1. March 11, 2009 at 6:40 pm, Satish said:

    I have following two steps in my script, how club them and do it in a single step ?

    tar -cf /home/eaips/var/fileName.tar /home/eaips/var/fileName
    gzip /home/eaips/var/fileName.tar


    • March 11, 2009 at 9:11 pm, Quinn McHenry said:

      it would be:

      tar -cf – /home/eaips/var/fileName | gzip -c > /home/eaips/var/fileName.tar.gz


  2. August 17, 2009 at 10:20 pm, Anonymous said:

    Or ‘tar zcf target.tgz’ Most tar versions have had built in gzip function for over a decade at least. Over ssh it would be ssh blah@blah ‘tar zcf -’ > target.tgz


  3. November 04, 2009 at 5:21 am, Vinayak Kamath said:

    You can use gtar instead

    gtar -cvzf target output.tgz


  4. February 14, 2010 at 7:27 pm, GlobalNerds said:

    How do you uncompress this in one step?


    • April 29, 2010 at 12:12 pm, Anonymous said:

      To Compress !
      tar cjf /dir1 file1 /dir2 …. /dirN /fileN => For Bunzip

      tar czf /dir1 file1 /dir2 …. /dirN /fileN => For Gunzip

      You can always use
      “man tar” when you need help !

      To Extract/uncompress , replace the “c” with “x” in the above commands !
      Thanks ,


  5. July 06, 2012 at 1:06 am, Squirrel said:

    One thing with above reply (at least for me) is that it should be tar c[jz]f outfile infiles…


Leave a Reply