How to use the tar and gzip commands with files in unix

The tar command is used to archive, or group, multiple files into one file.

Suppose our current working directory looks like this:

./
../
somefile.txt
anotherfile.log
somedirectory/
anotherdirectory/
yetanotherfile.dat

We could put a copy of somefile.txt, anotherfile.log, and somedirectory into a single tar file called mystuff.tar.

tar -cvf mystuff.tar somefile.txt anotherfile.log somedirectory/

Now our current directory would look something like this:

./
../
somefile.txt
anotherfile.log
somedirectory/
anotherdirectory/
yetanotherfile.dat
mystuff.tar

Now, to get the files out of the tar file we could do something like this:

mkdir files
mv mystuff.tar files/
cd files/
tar -xvf mystuff.tar

… which would make a new directory called files, move the tar file into the directory files, and pull the files out of the tar file. The files sub-directory would now look something like this:

./
../
somefile.txt
anotherfile.log
somedirectory/
mystuff.tar

tar is great, but we can make things even better and compress the archive with just a small change, using the gzip compression utility. Let’s replace our first example with the following:

tar -pczf mystuff.tar.gz somefile.txt anotherfile.log somedirectory/

This would create a compressed tar file in the current directory. To get the files back out we would do the following:

tar xvfz mystuff.tar.gz

To see a full list of options with these commands use the man command:

man tar
man gzip