In Linux “tar” is an archiving utility, which is used by a large number of Linux users to compress multiple files together into one file and then transfer it to other location and uncompress it. “TAR” is synonymous in functionality with “zip” on windows, although zip also is available on Linux.
The advantage of “tar” command is it can compress the files into highly compressed archive formats using called gzip, bzip, bzip2 compression thus reducing the final size significantly compared to Windows zip.
“TAR” thus helps to save disk space, time required for transferring files from one location to another and also the network bandwidth if we are transferring files from one PC to another.
tar [options] [archive-file-name.extention] [files or directory or directories to be archived]
The tar command provides the following options:
-c – create new archive file.
-x – extracts the archive file.
-f – Specifies the filename of the archive file.
-v -This prints information on terminal to understand whats happening when “compress” is going on.
-t – This lists all the files inside an archive file.
-u – This compress a file and then adds it to an existing archive file.
-r – This updates a file or directory located inside a .tar file
-z – Creates a tar file using gzip compression
-j – Create an archive file using the bzip2 compression
–w – The -w option verifies an archive file.
Now, lets understand this with one example, suppose we have a directory “workspace” which contains some files as below,
$ cd workspace
commands.txt file_exists.sh helloworld helloworld.c helloworld.map ifs.sh mydata.txt readline.sh readme.txt repo1 repo2 repo3
Now, we can archieve this in two ways,
1) archive complete workspace directory so when you decompress it will again create same directory and files inside it
2) archive the files / directories inside workspace directory so when you decompress, it will creates files in same directory where you are extracting.
For First Method, we need to go outside “workspace” directory,
$ cd ../
$ tar cvjf workspace.tar workspace/
$ file workspace.tar workspace.tar: bzip2 compressed data, block size = 900k
So, above command will archive entire folder and its contents.
For Second Method, you can be inside “workspace” directory and then add individual files or type “.” to add all files,
$ cd workspace
$ tar -cvjf workspace.tar .
Now, you can copy this “workspace.tar” to any location and extract using below command,
$ tar xvjf workspace.tar
i.e. just pass “x” to extract instead of “c” we used to compress.