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.

  • Satish

    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

    • http://www.tech-recipes.com Quinn McHenry

      it would be:

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

  • Anonymous

    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

  • http://www.facebook.com/vin.kamath Vinayak Kamath

    You can use gtar instead

    gtar -cvzf target output.tgz

  • http://www.globalnerds.com/ GlobalNerds

    How do you uncompress this in one step?

    • Anonymous

      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 ,
      Danny

  • Squirrel

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