Swiftorial Logo
Home
Swift Lessons
Tutorials
Learn More
Career
Resources

Using tar - File Compression

Introduction

The tar command in UNIX and UNIX-like operating systems is a powerful utility for creating, maintaining, modifying, and extracting files from a tar archive. The name "tar" stands for "tape archive", which is its original purpose. Today, it is widely used for file compression and archiving purposes.

Basic Syntax

The basic syntax for the tar command is:

tar [options] [archive-file] [file or directory to be archived]

Here, [options] are the command options, [archive-file] is the name of the archive file you want to create or operate on, and [file or directory to be archived] is the file or directory you want to include in the archive.

Creating an Archive

To create a new archive, you can use the -c option. For example:

tar -cvf archive_name.tar /path/to/directory

This command creates an archive named archive_name.tar containing the contents of /path/to/directory. The -v option enables verbose mode, showing the progress in the terminal.

Extracting an Archive

To extract an archive, you can use the -x option. For example:

tar -xvf archive_name.tar

This command extracts the contents of archive_name.tar in the current directory.

Appending Files to an Archive

To add files to an existing archive, use the -r option. For example:

tar -rvf archive_name.tar newfile.txt

This command appends newfile.txt to the existing archive_name.tar.

Listing the Contents of an Archive

To list the contents of an archive, use the -t option. For example:

tar -tvf archive_name.tar

This command lists all files contained in archive_name.tar.

Compressing with gzip

The tar command can also compress archives using gzip with the -z option. For example:

tar -czvf archive_name.tar.gz /path/to/directory

This command creates a gzip-compressed archive named archive_name.tar.gz.

Extracting a gzip-compressed Archive

To extract a gzip-compressed archive, use the -z option along with -x. For example:

tar -xzvf archive_name.tar.gz

This command extracts the contents of archive_name.tar.gz.

Compressing with bzip2

To compress archives using bzip2, use the -j option. For example:

tar -cjvf archive_name.tar.bz2 /path/to/directory

This command creates a bzip2-compressed archive named archive_name.tar.bz2.

Extracting a bzip2-compressed Archive

To extract a bzip2-compressed archive, use the -j option along with -x. For example:

tar -xjvf archive_name.tar.bz2

This command extracts the contents of archive_name.tar.bz2.

Conclusion

The tar command is a versatile and powerful tool for file compression and archiving. By mastering its options and understanding its capabilities, you can efficiently manage large sets of files and directories in UNIX and UNIX-like operating systems.