The tar
command in Linux is used to create, view, and manipulate archive files. An archive is a collection of multiple files and directories bundled into a single file, which can be compressed or uncompressed. The name “tar” stands for “tape archive,” as the command was initially developed for creating backups on magnetic tape storage. However, it is widely used for various purposes today.
The basic syntax of the tar
command is:
tar [options] [archive-filename] [file(s) or directory]
Here, options
are various flags that modify the behavior of the tar
command, archive-filename
is the name of the archive file you want to create or operate on, and [file(s) or directory]
is the list of files or directories you want to include in the archive.
Commonly Used Options:
- -c (or –create): Create a new archive.
- -x (or –extract): Extract files from an archive.
- -v (or –verbose): Verbose mode. Print the names of the files being processed.
- -f (or –file): Specifies the filename of the archive to create or operate on.
- -z (or –gzip): Compress the archive using gzip.
- -j (or –bzip2): Compress the archive using bzip2.
- -r (or –append): Append files to an existing archive.
- -t (or –list): List the contents of an archive.
- -u (or –update): Only append files that are newer than the archive contents.
- -p (or –preserve-permissions): Preserve file permissions and ownership when extracting.
- -C (or –directory): Change to a specific directory before performing operations.
Examples:
- Create a tar archive of a directory:
tar -cvf archive.tar directory_name
- Create a tar archive and compress it using gzip:
tar -czvf archive.tar.gz directory_name
- Extract files from a tar archive:
tar -xvf archive.tar
- List the contents of a tar archive:
tar -tvf archive.tar
- Append files to an existing tar archive:
tar -rvf archive.tar new_file
Note:
- The sequence of options holds crucial significance. For example, if you’re creating a compressed archive, you should specify the compression option (e.g.,
-z
or-j
) before the-f
option. - When extracting files from a compressed archive, the appropriate compression option (
-z
or-j
) should be used along with the-x
option. tar
does not provide encryption; it simply bundles files together. For secure storage or transmission, you might need to use additional tools likegpg
for encryption.
Remember that the tar
command is quite versatile and can be used in various combinations to suit your needs. Always consult the manual (man tar
) for more details and options.