How to Use Tar Command in Linux [16 Best Uses]

TL;DR

To effectively use the tar command in Linux, you can try these methods:

  1. Combine multiple files or directories into a single tar file with tar -cvf archive.tar /path/to/directory.
  2. Retrieve the contents of a tar file using tar -xvf archive.tar.
  3. View the files and directories within a tar file without extracting them by running tar -tvf archive.tar.
  4. Create compressed archive files using tar -czvf archive-name.tar.gz /path/to/directory for gzip or tar -cjvf archive-name.tar.bz2 /path/to/directory for bzip2 compression.
  5. Extract specific files from an archive with tar -xzvf archive-name.tar.gz path/to/specific/file, saving time and space.
  6. Update an existing archive by adding new files using tar -rvf archive-name.tar new-file, avoiding the need to create a new archive.

Read the guide below to learn how to use the Tar command in Linux and best practices to use the Tar command.

Managing files on Linux can be a real challenge, especially with so many files and directories to handle. But don’t worry, the tar command is here to help. It lets you bundle, compress, and manage your files easily. In this post, I’ll show you 16 different ways to use the tar command, from basic tasks to advanced techniques like encryption and automation. By the end, you’ll have practical skills to make your file management simpler and more efficient. Let’s make your Linux experience smoother.

What is Tar Command in Linux?

The tar command in Linux is a powerful tool used for creating, maintaining, extracting, and managing tar files—often referred to as tarballs. The name tar stands for Tape Archive, reflecting its original purpose for writing data to tape drives. This command is commonly used for file compression and archiving, allowing users to bundle a collection of files and directories into a single file. The resulting archive can be optionally compressed using additional utilities like gzip or bzip2.

Here are some basic usages of the tar command:

  • Creating an archive: tar -cvf archive_name.tar directory_to_archive/
  • Extracting an archive: tar -xvf archive_name.tar
  • Viewing the contents of an archive: tar -tvf archive_name.tar
  • Creating a compressed archive: tar -czvf archive_name.tar.gz directory_to_archive/ (using gzip)
  • Extracting a compressed archive: tar -xzvf archive_name.tar.gz

These options and utilities make tar an essential command for file management and data transfer in Linux environments.

How to Use Tar Command in Linux?

To use the tar command in Linux, you start by creating an archive with tar -cvf archive_name.tar directory_name, where -c creates the archive, -v shows the process, and -f specifies the filename. To extract an archive, use tar -xvf archive_name.tar, where -x extracts the files.

For viewing contents, use tar -tvf archive_name.tar, and to compress, add -z for gzip (tar -czvf archive_name.tar.gz directory_name) or -j for bzip2 (tar -cjvf archive_name.tar.bz2 directory_name).

Keeping reading the article below to learn 16 different methods to use the tar command in Linux:

1. Creating a Basic Archive

Creating a basic archive is essential for grouping multiple files or directories into a single file, making it easier to store and transfer them.

  1. Access your command line interface by pressing Ctrl+Alt+T.
opening-terminal
  1. Change the current working directory to where your files are located using:
cd /path/to/directory

Replace /path/to/directory with the directory name you want to compress.

navigating to directory
  1. Run the tar command to create the archive:
tar -cvf archive.tar /path/to/directory
  • -c: Create a new archive.
  • -v: Verbosely list files processed.
  • -f: Specifies the archive file name.

This command creates a tar archive named archive.tar from the specified directory.

creating archive of a specific directory

2. Extracting an Archive

Extracting an archive is necessary to retrieve the original files and directories from a tar archive.

  1. Access your command window and navigate to the directory.
  2. Run the tar command to extract the archive:
tar -xvf archive.tar
  • -x: Extract files from an archive.

This command extracts files from archive.tar.

extracting contents of archive

3. Listing Contents of an Archive

Listing the contents of an archive allows you to see what files and directories are stored in the archive without extracting them.

  1. Launch your Terminal window and go to your desired directory.
  2. Execute the following command:
tar -tvf archive.tar

This command lists the contents of archive.tar without extracting.

listing content of archive

4. Creating Compressed Archive Files

Compress files efficiently using tar with gzip or bzip2, reducing file size for easier storage and faster transmission. Essential for managing large datasets or backups. Follow these steps:

  1. Open your Terminal.
  1. Change the current working directory to where your files are located using.
  1. To create a gzip compressed archive, run the command: 
type tar -czvf archive-name.tar.gz /path/to/directory

If you are looking for quick compression then this method is best. 

creating gzip compressed archive using tar
  1. For the bzip2 compressed archive, use the command: 
tar -cjvf archive-name.tar.bz2 /path/to/directory

If you are looking for better compression, then this method is best.

creating bzip2 compressed archive using tar
  1. Confirm the creation of your compressed file by listing its details with the command: 
ls -lh archive-name.tar.*

This lists the details of the newly created archive, confirming its creation and size.

verifying the creation of compressed file

5. Extracting Specific Files from an Archive

Quickly extract specific files or directories from a tar archive without needing to decompress the entire archive, saving time and disk space in targeted retrievals. Here is the step-by-step guide:

  1. Launch the command line interface.
  2. Preview the contents of the archive by executing the command:
tar -tzvf archive-name.tar.gz 

Lists all files in the archive, helping you to identify specific file paths.

previewing specific files paths
  1. To extract specific files, run the command:
tar -xzvf archive-name.tar.gz path/to/specific/file

Verify the files have been extracted to the current directory.

extracting a specific file

6. Updating Files in an Archive

Updating files in an archive allows you to add or replace files in an existing tar archive without recreating it from scratch.

  1. Launch your Terminal window and go to the directory.Type the following command and press enter:
tar -uvf archive.tar updatedfile.txt

This command updates updatedfile.txt in archive.tar if it is newer than the existing file.

updating a file in the archive

7. Appending Files to an Existing Archive

Easily add new files to an existing tar archive. This feature is perfect for updating archive contents without creating a new archive from scratch.

  1. Access the command line and change to the directory where your archive is located.
  2. Add new files to the archive with: 
tar -rvf archive-name.tar new-file

Appends new files to the existing archive without recreating it.

adding new file to the archive
  1. Confirm the addition by listing the archive’s contents by running the command: 
tar -tvf archive-name.tar

The output will be:

verifying the addition of the file to the archive

8. Excluding Files from an Archive

Excluding files or directories from an archive is useful when you want to archive a directory but omit certain files or subdirectories.

  1. Access your command window and navigate to the directory where the files are located.
  2. Run the following command to create the archive while excluding specific files:
tar --exclude=/home/guestuser/Downloads/file1.txt -cvf archive.tar /home/guestuser/Downloads

This command creates a tar archive while excluding the specified path.

creating archive while excluding a specific file

9. Splitting an Archive into Multiple Files

Splitting a large archive into smaller parts is useful for easier storage, transfer, or handling when dealing with size limits on files.

  1. Open your Terminal and move to the desired directory. Type the following command and press Enter:
tar -cvf - /path/to/directory | split --bytes=500MB - archive.tar.part

This command creates a tar archive and splits it into multiple parts of 500MB each.

splitting an archive in multiple files

10. Preserving File Permissions and Ownership

Preserving file permissions and ownership is crucial when archiving system files or directories to ensure they retain their original properties when extracted.

  1. In your Terminal, run the following command to create the archive while preserving permissions and ownership:
tar -cvp --preserve-permissions --file=archive.tar /path/to/directory

This command creates a tar archive while preserving file permissions and ownership.

creating a archive while preserving files permissions and ownerships

11. Comparing Archive Contents with the File System

Ensure data integrity by comparing the contents of a tar archive with the file system, identifying discrepancies and ensuring accurate backups or archives. Follow these steps to compare the archive content:

  1. Launch your command line tool.
  2. Compare the archive contents against the file system by typing the command: 
tar -dvf archive-name.tar
  1. Analyze the output for any discrepancies or missing files.
comparing archive contents with the file system 1

12. Creating Incremental Backups

Save disk space and backup time by creating incremental backups with tar, which only archives changes since the last backup, ideal for regular backup routines. Here is how to do it:

  1. Begin by accessing your command line interface.
  2. Create a full backup by using the following command: 
tar -czvf full-backup.tar.gz /path/to/directory

Replace the /path/to/directory with the directory name of which you want to create backup.

creating full backup archive
  1. For incremental backups, use the command: 
tar --listed-incremental=/path/to/snapshot.file -czvf incremental-backup.tar.gz /path/to/directory

Creates backups of changes since the last backup, saving space and time.

creating incremental backup of a directory

13. Securing Tar Archives with Encryption

Enhance the security of your tar archives by encrypting them. This method is crucial for protecting sensitive data in storage or transit. Here is the step-by-step guide:

  1. Access your command line tool.
  2. Encrypt your tar archive by running the command: 
gpg -c archive-name.tar.gz

Secures your archive by encrypting it with a password.

encrypting tar archive
  1. To access the contents later, decrypt with the command: 
gpg archive-name.tar.gz.gpg

The encrypted archive will be decrypted.

decrypting archive content

14. Automating Tar Tasks with Scripts

Streamline repetitive tar operations by automating them with scripts. This approach increases efficiency and consistency in backup and archiving processes. Steps to automate tar tasks with scrips are:

  1. Use a text editor to write your tar command(s) in a .sh file.
creating automating tar script
  1. Change the script’s permissions to executable with:
chmod +x your-script.sh

Makes the script file executable, allowing it to run as a program.

making the script file executable
  1. Execute the script by typing: 
./your-script.sh

Runs the script to automate the tar tasks you’ve defined.

executing the script file

15. Extracting Archives to Specific Directories

Directly extract tar archives to specific directories, enabling organized data management and restoration processes without cluttering the working directory. Follow these steps:

  1. Access the command line interface.
  2. To extract an archive to a specific directory, execute the command: 
tar -xzvf archive-name.tar.gz -C /target/directory

Replace target/directory with the name of the directory in which you want to extract the files.

extracting archive to another directory
  1. Check the specified directory to ensure the files were extracted correctly.

16. Using Tar with Pipes for Efficient Workflows

Leverage piping with tar for efficient data transfer between commands, minimizing disk usage and streamlining data backup and restoration workflows. Here is the guide:

  1. Launch the command line.
  2. Directly compress and backup a directory by running the command: 
tar cvf - /path/to/directory | gzip > archive-name.tar.gz

Compresses and backs up a directory in one step, using pipes to pass data between commands.

compress and backup a directory
  1. For restoration, decompress and extract with the command:
gzip -dc archive-name.tar.gz | tar xvf -

The command will restore the backed-up compressed directory.

decompress and extract the archive

5 Best Practices for Using Tar in Linux

When working with tar in Linux, adopting best practices can significantly enhance your efficiency and data management. These practices ensure your archives are well-organized, secure, and easy to handle, whether you’re backing up data or sharing files. Here are five best practices to follow when using Tar in Linux:

  • 📦 Use Descriptive Filenames: When creating tar archives, choose descriptive filenames that include the date of creation and content description. This practice helps in quickly identifying the purpose and age of an archive without needing to open it.
  • 🔒 Secure Your Archives: Always encrypt sensitive data using tools like gpg before sharing or storing. Encryption adds a layer of security, protecting your data from unauthorized access during transit or in storage.
  • 🔄 Verify Archives After Creation: Use the tar -tvf command to list the contents of an archive after creation. This step ensures all intended files and directories are included and there are no errors.
  • 🚀 Leverage Compression Efficiently: Choose the right compression method (gzip for speed, bzip2 for smaller size) based on your needs. Compression reduces file size, making storage and transfer more efficient but can increase processing time.
  • 🛠 Incorporate Incremental Backups: Instead of full backups, use incremental backups to save only changed files after the initial full backup. This approach saves disk space and speeds up the backup process, making it ideal for regular backups.

Tar Command Linux: In a Nutshell

In this article, I’ve walked you through 16 methods for using the tar command in Linux, from basic archiving to advanced techniques like incremental backups and encryption. These methods will help you manage files efficiently and securely. Remember to use descriptive filenames, verify archives, and choose the right compression methods to make the most out of tar.

For more learning, you should check out:

  • Understanding various methods to extract tar files will expand your knowledge on file retrieval techniques.
  • Enhancing your skills in handling compressed files by learning how to unzip and extract Gz files in Linux.
  • Boosting your command-line proficiency by mastering the exec command, which provides powerful tools for executing commands in different contexts.

Frequently Asked Questions

  1. How can I recover data from a corrupted tar archive?

    To recover data from a corrupted tar archive, try using tar -xvf for partial extraction or seek specialized recovery software. The success rate depends on the corruption level. For highly valuable data, consider professional data recovery services, which might offer more advanced recovery options.

  2. Are there any GUI tools that can handle tar operations for beginners?

    Beginners can use GUI tools like PeaZip, 7-Zip, and File Roller for managing tar operations. These tools provide user-friendly interfaces for creating, extracting, and viewing tar archives, eliminating the need for command-line interactions and making tar operations more accessible.

  3. What are the limitations of tar compared to modern file compression tools?

    Compared to modern compression tools, tar may exhibit slower compression speeds and produce larger file sizes. However, it is highly effective for archiving multiple files into one bundle and enjoys broad support across different platforms, making it a reliable choice for many users.

  4. Can I update files within a tar archive without extracting them?

    Updating files directly within a tar archive without extracting them is generally not supported due to tar’s design for bundling rather than file editing. The common approach is to extract the archive, update the necessary files, and then create a new archive with the changes.

  5. How do I list the contents of a tar archive without using the terminal?

    To list the contents of a tar archive without the terminal, utilize GUI tools like WinRAR, 7-Zip, or File Roller. These applications allow users to easily view the contents of tar archives through a graphical interface, making it straightforward for those less familiar with command-line tools.

Ojash

Author

Ojash is a skilled Linux expert and tech writer with over a decade of experience. He has extensive knowledge of Linux's file system, command-line interface, and software installations. Ojash is also an expert in shell scripting and automation, with experience in Bash, Python, and Perl. He has published numerous articles on Linux in various online publications, making him a valuable resource for both seasoned Linux users and beginners. Ojash is also an active member of the Linux community and participates in Linux forums.

Akshat

Reviewer

Akshat is a software engineer, product designer and the co-founder of Scrutify. He's an experienced Linux professional and the senior editor of this blog. He is also an open-source contributor to many projects on Github and has written several technical guides on Linux. Apart from that, he’s also actively sharing his ideas and tutorials on Medium and Attirer. As the editor of this blog, Akshat brings his wealth of knowledge and experience to provide readers with valuable insights and advice on a wide range of Linux-related topics.

Share this article
Shareable URL
Prev Post

5 Ways To Use ls Command to Sort Files by Size in Linux

Next Post

How to Extract Tar Files in Linux? [2 Best Methods]

Leave a Reply

Your email address will not be published. Required fields are marked *

Read next