Skip to content

tar Command in Linux: Archiving and Extracting Files

Summary

The tar command is a powerful archiving utility in Linux used to create tar archives (also known as tarballs) and extract files from them. These archives are commonly used for software distribution, backups, and transferring large sets of files.

Introduction

The tar command, short for "tape archive," is a fundamental utility in Linux systems. It's designed to bundle multiple files and directories into a single archive file. While tar itself doesn't compress the data (though it is often confused with compression), it's frequently used in conjunction with compression tools like gzip or bzip2 to create compressed archives (e.g., .tar.gz, .tar.bz2).

Use case and Examples

Creating a tar archive

tar -cvf archive.tar file1 file2 directory1
This command creates a tar archive named archive.tar containing file1, file2, and the contents of directory1. The c option creates the archive, v makes the process verbose (shows the files being added), and f specifies the archive filename.

Extracting a tar archive

tar -xvf archive.tar
This command extracts the contents of archive.tar into the current directory. The x option extracts the archive, v makes the process verbose, and f specifies the archive filename.

Creating a gzipped tar archive

tar -czvf archive.tar.gz file1 file2 directory1
This command creates a gzipped tar archive named archive.tar.gz containing file1, file2, and the contents of directory1. The z option tells tar to use gzip for compression.

Extracting a gzipped tar archive

tar -xzvf archive.tar.gz
This command extracts the contents of archive.tar.gz into the current directory. The z option tells tar to use gzip for decompression.

Listing the contents of a tar archive

tar -tvf archive.tar
This command lists the contents of archive.tar without extracting them. The t option lists the table of contents of the archive.

Extracting a specific file from a tar archive

tar -xvf archive.tar file1
This command extracts only file1 from the archive.tar.

Commonly used flags

Flag Description Example
-c Create a new archive. tar -cvf archive.tar file1 file2
-x Extract files from an archive. tar -xvf archive.tar
-t List the contents of an archive. tar -tvf archive.tar
-v Verbose mode. Shows the files being processed. tar -cvvf archive.tar file1 (more verbose)
-f Specify the archive filename. tar -cvf myarchive.tar files
-z Compress the archive with gzip. tar -czvf archive.tar.gz files
-j Compress the archive with bzip2. tar -cjvf archive.tar.bz2 files
-C <directory> Change to the specified directory before creating or extracting the archive. tar -xvf archive.tar -C /tmp
--exclude=<pattern> Exclude files matching the specified pattern. tar -cvf archive.tar --exclude="*.log" files


Share on Share on

Comments