tar
The tar
command in Linux is a highly versatile tool used for file archiving and compression. The name tar
stands for "Tape Archive", a throwback to its original purpose for writing data to tape drives. It allows multiple files and directories to be bundled together into a single archive file (commonly known as a tarball), and optionally compress it for space efficiency. Here are the key aspects and functionalities of the tar
command:
Creating Archives: To create a tarball,
tar
is used with the-c
(create) option, along with-f
to specify the filename of the archive. For example,tar -cf archive.tar file1 file2 dir1
will create an archive file namedarchive.tar
containingfile1
,file2
, anddir1
.Viewing Archive Contents: To view the contents of a tarball without extracting it, use the
-t
(list) option. For example,tar -tf archive.tar
lists the contents ofarchive.tar
.Extracting Archives: To extract the contents of a tarball, use the
-x
(extract) option. For example,tar -xf archive.tar
will extract the contents ofarchive.tar
into the current working directory.Compression:
tar
can be combined with compression methods like gzip or bzip2. To create a compressed tarball, you use additional options:-z
for gzip (resulting in.tar.gz
or.tgz
files) or-j
for bzip2 (resulting in.tar.bz2
files). For example,tar -czf archive.tar.gz directory
will create a gzipped tarball ofdirectory
.Decompressing and Extracting: To extract a compressed tarball, you include the same compression option. For example,
tar -xzf archive.tar.gz
will extract the contents of a gzipped tar archive.Appending Files to an Archive: The
-r
option allows you to append files to an existing tarball. Note that this doesn’t work with compressed archives.Updating an Archive: The
-u
option is used to update files within an archive that have changed since the archive was created.Preserving Permissions:
tar
preserves file permissions and ownership in the archive, which makes it a popular choice for backups and transferring files between systems.Piping and Redirection:
tar
can be used with piping and redirection in Linux. For example, you can pipe the output oftar
tossh
for remote backups or use it with other commands for advanced file processing tasks.
Last updated