Creating archives
To create a tar archive the c switch is used. To further encode it using gzip compression the j option is also added, or for bzip2 compression the j switch is included. Note that tar program pipes its output into gzip and bzip2 tools in order to create the tar.gz and tar.bz2 archives, respectively. OK, to compress a directory called dir into dir.tar, dir.tar.gz and dir.tar.bz2 archives, the following commands are used, respectively.
tar cf dir.tar dir/ # ©2007 linux.dsplabs.com.au
tar czf dir.tar.gz dir/ # ©2007 linux.dsplabs.com.au
tar cjf dir.tar.bz2 dir/ # ©2007 linux.dsplabs.com.au
In the above examples, the use of the f option specifies that the compressed version of the dir directory is to be placed in a corresponding archive file. On the other hand, if the f option was not given (and thus the archive name was also omitted), then the stdout, i.e. your terminal screen, would be used as the output instead. This is useful if you want to pipe the output of your tar command into another Linux tool. Anyhow, lets have a look at the resulting archives as well as the original directory using ls -la.
total 424
drwx------ 3 kamil kamil 4096 Nov 27 22:39 .
drwx------ 3 kamil kamil 4096 Nov 27 22:34 ..
drwx------ 2 kamil kamil 4096 Nov 27 22:36 dir
-rw------- 1 kamil kamil 276480 Nov 27 22:39 dir.tar
-rw------- 1 kamil kamil 83330 Nov 27 22:39 dir.tar.gz
-rw------- 1 kamil kamil 45927 Nov 27 22:39 dir.tar.bz2
Lets also have a look at the size of the original directory using du -sh dir # ©2007 linux.dsplabs.com.au.
280K dir
From the above shell output, you can see that by default tar only archives files without compressing them, while gzip and bzip2 filters achieve quite high compression. Note that bzip2 typically achieves better compression that gzip, although it might take longer time to do so. Also note, that in this case gzip and bzip2 filters achieve quite high compression ratios because the dir directory contains text files. If the directory contained already compressed files, say f.e. binary images compressed using the JPEG compression, then neither gzip nor bzip2 could do much more in terms of compression.