Learn about tar command in Linux

A penguin with a speech bubble that says learn about tar command in Linux.

The tar command in Linux is used to create, view, and manipulate archive files. An archive is a collection of multiple files and directories bundled into a single file, which can be compressed or uncompressed. The name “tar” stands for “tape archive,” as the command was initially developed for creating backups on magnetic tape storage. However, it is widely used for various purposes today.

The basic syntax of the tar command is:

tar [options] [archive-filename] [file(s) or directory]

Here, options are various flags that modify the behavior of the tar command, archive-filename is the name of the archive file you want to create or operate on, and [file(s) or directory] is the list of files or directories you want to include in the archive.

Commonly Used Options:

  1. -c (or –create): Create a new archive.
  2. -x (or –extract): Extract files from an archive.
  3. -v (or –verbose): Verbose mode. Print the names of the files being processed.
  4. -f (or –file): Specifies the filename of the archive to create or operate on.
  5. -z (or –gzip): Compress the archive using gzip.
  6. -j (or –bzip2): Compress the archive using bzip2.
  7. -r (or –append): Append files to an existing archive.
  8. -t (or –list): List the contents of an archive.
  9. -u (or –update): Only append files that are newer than the archive contents.
  10. -p (or –preserve-permissions): Preserve file permissions and ownership when extracting.
  11. -C (or –directory): Change to a specific directory before performing operations.

Examples:

  1. Create a tar archive of a directory:
tar -cvf archive.tar directory_name
  1. Create a tar archive and compress it using gzip:
tar -czvf archive.tar.gz directory_name
  1. Extract files from a tar archive:
tar -xvf archive.tar
  1. List the contents of a tar archive:
tar -tvf archive.tar
  1. Append files to an existing tar archive:
tar -rvf archive.tar new_file

Note:

  • The sequence of options holds crucial significance. For example, if you’re creating a compressed archive, you should specify the compression option (e.g., -z or -j) before the -f option.
  • When extracting files from a compressed archive, the appropriate compression option (-z or -j) should be used along with the -x option.
  • tar does not provide encryption; it simply bundles files together. For secure storage or transmission, you might need to use additional tools like gpg for encryption.

Remember that the tar command is quite versatile and can be used in various combinations to suit your needs. Always consult the manual (man tar) for more details and options.

Leave a Comment

Scroll to Top