Trusted answers to developer questions

How to use tar for archiving

Get the Learn to Code Starter Pack

Break into tech with the logic & computer science skills you’d learn in a bootcamp or university — at a fraction of the cost. Educative's hand-on curriculum is perfect for new learners hoping to launch a career.

If you are running a Linux Distribution, Mac OS X, or other Unix-like operating systems, your system will already have the tar program.

You can check the tar manual by typing $man tar in the terminal.

How to unpack a tarball

  1. To unpack a tarball, use the following command:

    $ tar xvf <tarball>

    In this command, the x stands for extract, v stands for verbose output, and f represents the filename of the archive.

  2. To uncompress a gzip-compressed tar, use option z in addition to the command above.

    $ tar xvzf <tarball>

    The z stands for uncompressing a gzip archive.

  3. To uncompress a bzip2 compressed tar, use option j instead of z:

    $ tar xvjf <tarball>

How to create a tarball

  1. To create a tar archive, use the command below:

    $ tar cvf <tarball name> <file/directory to be archived>

    The c stands for create archive, v stands for the verbose list files that have been processed, and f represents the filename of the archive.

  2. To create a compressed archive, use the following command:

    $ tar cvzf <tarball name> <file/directory to be archived>

    This creates a gzip-compressed archive.

  3. To create a bzip2 compressed archive, use option j:

    $ tar cvjf <tarball name> <file/directory to be archived>

  4. To add a file or directory to an existing archive, use the following command:

    $ tar rvf <tarball name> <file/directory to be added>

    You cannot add a file or directory to a compressed archive.

How to list an archive

You can use the following command to view the tar content before extraction:

$ tar tvf <tarball>

For a compressed archive, you can use the options j or z, depending on the type of compression.

How to extract a single file

To extract a single file from the archive, you can specify the name of the file at the end of the extract command:

tar xvf <tarball> <path to file>

If we specify a directory instead of a file, the directory will be extracted from the path.

We can also specify multiple files or directories for extraction.

Wildcards can also be used to extract files that match a specific pattern.

RELATED TAGS

tar

CONTRIBUTOR

Anjana Shankar
Attributions:
  1. undefined by undefined
Did you find this helpful?