Get a Free Storage Extension on your new VPS! More space, more possibilities.

Linux tar Command Guide: How to Use It 

If you have ever downloaded open-source software or moved a complex directory structure between servers, you have likely encountered the tar command. Short for “Tape Archive,” tar is one of the most essential utilities in the Linux toolkit. Its primary job is to bundle multiple files and directories into a single archive file, often referred to as a “tarball.” 

Historically, this tool was designed to write data sequentially to magnetic tape drives for backup purposes. But what is tar in Linux primarily used for? It serves as the standard format for file distribution and system backups. Unlike a standard copy command, tar preserves vital file metadata, such as permissions, dates, and directory structures. This makes it indispensable when you need to migrate data or safeguard the file system of a Linux VPS or Dedicated Server

It is important to note the distinction between archiving and compression. By default, the tar command in Linux only groups files together without reducing their size. However, it is almost always paired with compression utilities like Gzip or Bzip2 to save disk space, resulting in familiar file extensions like .tar.gz or .tar.bz2. Whether you are performing a quick backup or deploying an application, mastering this tool is a fundamental skill for navigating the Linux terminal. 

tar Command Syntax & Structure 

Understanding the basic structure of the command is the first step to using it without errors. The linux tar command follows a specific order of operations that tells the system exactly what action to perform, where to put the result, and which files to include. 

The general syntax looks like this: 

tar [options] [archive-name] [files-or-directories]

Here is a breakdown of those three components: 

  • Options: These are single-letter flags (like -c or -v) that define the operation. They determine if you are creating a new archive, extracting an existing one, or simply listing contents. 
  • Archive Name: This is the name you assign to the output file, such as backup.tar. 
  • Files or Directories: This is the target data you want to process. You can specify a single file, a whole folder, or a list of multiple items separated by spaces. 

A practical example helps clarify this. If you wanted to create an archive named photos.tar containing a folder named /images, the command would be: 

tar -cvf photos.tar /home/user/images

In this example, the flags -cvf tell the system to create a new archive, show verbose output (displaying the process on screen), and output to a specific file. Mastering this tar command syntax is vital because the order of flags matters specifically, the f flag must usually be immediately followed by the archive name, or the command will fail. 

tar Options and Flags

The real power of the utility lies in its versatility, which is controlled entirely through flags. While there are dozens of linux tar options available in the manual pages, you only need to memorize a handful to handle 99% of daily administration tasks. These flags can often be combined into a single string (e.g., -cvf) to save typing time. 

Here are the most essential tar command flags broken down by function: 

Operation Flags

These tell the command what main action to take. You generally use only one of these at a time. 

  • -c (–create): Creates a new archive file. 
  • -x (–extract): Extracts the contents of an existing archive. 
  • -t (–list): Lists the contents of an archive without extracting them (useful for inspecting a file before unpacking it). 
  • -r (–append): Appends files to the end of an existing archive. 
  • -u (–update): Appends files only if they are newer than the copy in the archive. 

General Options

These modify how the operation is performed or provide feedback. 

  • -v (–verbose): Displays the progress in the terminal, showing each file as it is processed. Without this, the command runs silently. 
  • -f (–file): Specifies the filename of the archive. This is mandatory for almost all operations involving a specific file. 
  • -p (–preserve-permissions): Retains the original file permissions (users, groups, access modes) of the archived data. 

Compression Flags

These tar flags automatically pass the archive through a compression algorithm. 

  • -z: Compress using gzip (fast, widely compatible). Creates .tar.gz. 
  • -j: Compress using bzip2 (better compression, slower). Creates .tar.bz2. 
  • -J: Compress using xz (high compression, very slow). Creates .tar.xz. 

When combining these, remember that the order is flexible, except for -f. A good rule of thumb is to place -f at the very end of your options string so the filename follows immediately after it. 

tar Command Examples for Files and Directories

Theory is helpful, but seeing tar examples in action is the best way to learn. Whether you are backing up a website or moving configuration files, the process remains consistent. The following scenarios cover the most frequent tasks you will encounter when managing a Linux system. 

How to Tar Directories

The most common use case is bundling an entire folder into a single file. This is often done before moving a directory to another server to ensure no files are lost during the transfer. To archive a directory named /var/www/html into a file named web-backup.tar, you would run: 

tar -cvf web-backup.tar /var/www/html

In this tar command example, the system recursively includes every file and subfolder inside the html directory. The verbose flag (-v) will print the list of files as they are being added, giving you visual confirmation that the process is working. 

How to Tar Files

Sometimes you do not need the whole directory, but only specific files. You can list as many individual files as you need after the archive name. For instance, if you want to back up only the configuration files and an error log, the command looks like this: 

tar -cvf config-backup.tar config.php error.log .htaccess

This flexibility allows you to be precise. You can even combine these approaches by listing a directory followed by specific files. The tar command simply grabs everything you list and packs it into the destination archive. 

Archiving Files with a Wildcard

If you need to archive all files of a certain type, such as all log files in a folder, you can use a wildcard (*). This saves you from typing every filename manually: 

tar -cvf logs-backup.tar *.log

This command searches the current directory for any file ending in .log and adds it to the archive. It is a quick way to organize messy directories or isolate specific data types for storage. 

Compressing Archives with tar

While grouping files into a single archive is useful, it does not reduce the total file size on its own. To save disk space and reduce transfer times, you need to combine the archive process with compression. The tar compress command functionality is built directly into the tool, allowing you to archive and compress in a single step using specific flags. 

Gzip Compression (Speed)

Gzip is the most widely used compression method in Linux because it is fast and supported by virtually every system. It offers a decent reduction in size without consuming too much CPU power. To compress file with tar using Gzip, add the -z flag. 

  • Command: tar -czvf archive.tar.gz directory/ 
  • Result: A .tar.gz or .tgz file. 

Bzip2 Compression (Size)

If saving space is more important than speed, Bzip2 is a strong alternative. It compresses files more tightly than Gzip but takes slightly longer to process. This is ideal for archiving large logs or text files where size reduction is critical. Use the -j flag for this format. 

  • Command: tar -cjvf archive.tar.bz2 directory/ 
  • Result: A .tar.bz2 file. 

XZ Compression (Maximum Efficiency)

For the highest possible compression ratio, XZ is the modern standard. It is significantly slower than the other options, especially when creating the archive, but it produces the smallest possible files. This is perfect for long-term backups where you rarely need to access the data. Use the -J (capital J) flag. 

  • Command: tar -cJvf archive.tar.xz directory/ 
  • Result: A .tar.xz file. 

Choosing the right format depends on your needs: use Gzip for everyday tasks and XZ when you need to squeeze every megabyte of space out of your storage. 

Extracting Archives with tar

Getting files out of an archive is just as important as putting them in. The primary tool for this is the extract flag, represented by -x. When you run a tar extract command, the system reads the archive and recreates the original directory structure and files exactly as they were stored. 

To extract a standard archive in your current directory, you use the flags -xvf. 

tar -xvf archive_name.tar

This unpacks everything into the folder you are currently working in. 

Modern versions of tar are smart enough to automatically detect compression. This means you do not always need to specify the compression flag (like -z or -j) when unpacking. Whether it is a .tar.gz or a .tar.bz2 file, the simple extract command usually works. 

tar -xvf archive_name.tar.gz

Sometimes you want to extract files into a different folder to avoid cluttering your current workspace. You can do this without moving the archive file by using the -C (change directory) option. This tells the command to unpack the contents into a specific destination path. 

tar -xvf archive_name.tar.gz -C /path/to/destination

Be careful when extracting files, as tar will overwrite any existing files with the same names without asking for confirmation. It is always a good habit to list the contents using the -t flag first to ensure you know exactly what is about to be unpacked. 

Advanced tar Command Examples for Linux and Unix

Once you are comfortable with creating and extracting archives, you can start using more sophisticated techniques to gain finer control over your file management. These linux tar examples demonstrate how to handle specific scenarios that often arise during server administration or complex backups. 

Excluding Files and Directories

There are times when you want to archive a directory but leave out certain files, such as temporary cache files or hidden git folders. You can use the –exclude option to filter these out. It is important to place this flag before the source directory in the command line. 

tar -czvf backup.tar.gz --exclude='*.log' --exclude='.git' /var/www/project

This command creates an archive of the project folder but ignores any file ending in .log and the entire .git directory. This keeps your backups clean and significantly smaller. 

Extracting a Single File

You do not always need to unpack an entire 10GB archive just to retrieve one accidentally deleted configuration file. You can extract specific items by adding the file path after the command. 

tar -xvf backup.tar.gz home/user/config.xml

This creates a unix tar example of efficiency: the command scans the archive, finds config.xml, and extracts only that file, leaving the rest of the archive untouched. 

Verifying Archive Contents

Before restoring a backup, it is wise to check what is inside without actually extracting it. This prevents overwriting current data with outdated files. The -t flag handles this. 

tar -tvf backup.tar.gz

This outputs a detailed list of every file, its permissions, owner, and timestamp. It acts as a table of contents, allowing you to verify that the archive contains the correct data before you commit to extracting it. 

Preserving Permissions

For system backups, retaining file ownership and permission settings is vital. While tar tries to do this by default for the superuser (root), you can force this behavior using the -p flag. 

tar -cvpf full-backup.tar /home/user

This ensures that when you extract the files later, the executable rights and user ownerships remain exactly as they were on the original system. 

Common Usage Patterns and Best Practices

Mastering the tar command goes beyond simply memorizing flags; it involves adopting workflows that prevent data loss and streamline your operations. Experienced Linux administrators rely on specific patterns to ensure their archives are safe, identifiable, and easy to restore. 

Standardize Your Naming Conventions

A common mistake is creating archives named backup.tar or data.tar.gz. If you create a second backup a week later, you risk overwriting the first one. A solid tar command usage habit is to append the date to every archive filename. 

tar -czvf website-backup-$(date +%F).tar.gz /var/www/html

This command automatically generates a file like website-backup-2023-10-25.tar.gz. This simple trick makes your archives easy to sort and identify, ensuring you never accidentally destroy an older, vital backup. 

Use Relative Paths, Not Absolute Paths 

When archiving, try to navigate to the parent directory first rather than using the full path from the root. If you archive using an absolute path (like /home/user/data), extracting that archive might force the files back into that exact location, potentially overwriting newer versions of files on the destination server. By using relative paths (like ./data), you retain the flexibility to extract the folder anywhere you choose. 

Verify Before You Delete

It is tempting to run a command that archives a folder and immediately deletes the original to save space. However, if the archive process fails or gets interrupted, you could lose everything. The best practice is to run the archive command, verify the integrity of the new file using the list flag (-t), and only then remove the source files. 

Piping over SSH

One of the most powerful usage patterns involves sending data directly to another server without creating a temporary file on your local machine. This is ideal when you are low on disk space. 

tar -cvf - /source/folder | ssh user@remote_server "tar -xvf - -C /destination/folder" 

In this pipeline, the – represents standard output. You are essentially streaming the tar command output through an SSH tunnel and extracting it immediately on the other side. This copies the directory structure perfectly across the network in one smooth action. 

tar Command FAQ

Here are answers to the most frequently asked questions about using this utility. 

What is tar in Linux?

Tar (Tape Archive) is a command-line utility used to group multiple files and directories into a single archive file. It is the standard tool in Linux for packaging software, backing up data, and distributing files. While it bundles files together, it is often combined with compression tools like Gzip to reduce the file size. 

How to use tar?

You use tar by combining specific flags to tell the system what you want to do. The basic structure is tar [flags] [archive-name] [files]. The three most critical flags to know are -c to create an archive, -x to extract one, and -f to specify the filename. 

How to tar a folder in Linux?

To archive an entire folder, use the create -c and verbose -v flags along with the file -f flag. 

Command:

tar -cvf archive-name.tar /path/to/folder 

This creates an uncompressed archive of the specified folder. 

How to tar a file in Linux?

The process for a single file is identical to a folder. You simply point the command to the specific filename instead of a directory. 

Command:

tar -cvf archive-name.tar filename.txt

You can also list multiple files separated by spaces to include them all in one archive. 

How do I use the tar xvf command to extract archives?

The xvf flag combination stands for eXtract, Verbose, and File. It tells Linux to unpack an archive, show you the progress on the screen, and read from the file you specify. 

Command:

tar -xvf archive-name.tar 

This will extract the contents of the archive into your current working directory. If the file is compressed (like .tar.gz), you can usually use this same command, as modern tar versions auto-detect the compression format. 

Conclusion

Mastering the tar command is a fundamental skill for anyone managing a Linux environment. It provides a robust, flexible way to handle file storage, backups, and transfers with precision. From bundling complex directory structures to compressing large datasets for migration between a Linux VPS and a local machine, this tool remains one of the most reliable utilities in the terminal. 

By understanding the basic syntax and the power of flags like -z, -x, and -v, you can streamline your daily system administration tasks. Whether you are performing a quick file backup or deploying a full application stack, the ability to effectively archive and extract data ensures your workflow remains efficient and your data secure. As you continue to work with Linux, these commands will become second nature, forming the backbone of your file management strategy. 

Scroll to Top