Linux often uses two particular utilities to help manage files. The first utility is tape archiver or tar. The second is a compression utility such as gzip. The purpose of tar is to bundle together multiple files into a single tarball with a .tar extension. This makes functions like downloads much easier since there is only one download necessary to acquire multiple files. The server administrator creates the bundle of files, and whoever downloads the bundle extracts the files from it.

It is essential to know how to work with tar because a great deal of the software available for Linux is distributed in tarballs. The following is an example of creating a tarball:

$ tar -cvf tarball.tar file1 file2 file3

This bundles file1, file2, and file3 into a tarball named tarball.tar.

tar Command Options

The basic options for the tar command are as follows.

Option Used To
-c Create the tarball.
-x Extract the tarball.
-v Enable verbose mode.
-r Append more files to an existing tarball.
-t Test the tarball or see what files are included in the tarball.
-f Specify the name of the tarball in the next argument (must be used as the last option).

tar Command Examples

1. To create an archive:

# tar -cvf test.tar test1 test2 test3 test4
# tar -cvf test.tar test*
# tar -cvf etc.bk /etc 

2. To display the content of the tar ball

3. To extract the tar ball:

4. To add / append a file into the tar ball:

# tar --append -f test.tar test5 

5. To delete / remove a files from the tar ball:

# tar --delete -f test.tar test6 

6. Extract single file from tar ball:

# tar -xvf test.tar test4
# tar -xvf test.tar /tmp/test4 

7. Extract multiple files from tar ball:

# tar -xvf test.tar "test1" "test2" 

8. Extract group of files from tar ball:

# tar -xvf test.tar "*.test" 

9. Add / append files or directories to tar ball:

10. To verify the tar ball:

11. Finding the difference between gzip archive file and file system:

12. Finding the difference between bzip2 archive file and file system:

13. Creating a gzipped tar ball/archive:

# tar -czvf test.tar.gz /tmp 

14. Creating a bzip2 tar ball/archive:

# tar -jcvf test.tar.bz2 /tmp 

15. Extract gzip / bzip2 tar ball:

# tar -xvf test.tar.gz
# tar -xvf test.tar.bz2

16. List the contents for gzip / bzip2 tar ball:

# tar tvf test.tar.gz
# tar tvf test.tar.bz2 

17. Extract single files from gzip / bzip2 tar archives:

# tar -jxvf test.tar.bz2
# tar -zxvf test.tar.gz 

18. Extract group of files from gzip / bzip2 tar archives:

# tar -jxvf test.tar.bz2 --wildcards "test*"
# tar -zxvf test.tar.gz --wildcards "test*" 

19. To take the backup of any file system:

# tar -cvf etc.bk /etc
# tar -cvf tmp.bk /tmp
# tar -cvf var.bk /var
# tar cvf boot.bk /boot 

20. To backup your system:

# tar -cvpzf backup.tar.gz --exclude=/backup.tar.gz --one-file-system /