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
This command creates a tar archive namedarchive.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
This command extracts the contents ofarchive.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
This command creates a gzipped tar archive namedarchive.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
This command extracts the contents ofarchive.tar.gz
into the current directory. The z
option tells tar
to use gzip
for decompression. Listing the contents of a tar archive
This command lists the contents ofarchive.tar
without extracting them. The t
option lists the table of contents of the archive. Extracting a specific file from a tar archive
This command extracts onlyfile1
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 |