Archiving Files with the Tar Command
The tar
command is a powerful tool in Linux that allows you to create and manage archive files, commonly known as "tarballs." Tarballs can contain multiple files and directories, and they can be further compressed using various compression formats.
Creating a Tarball
To create a new tarball, you can use the following basic syntax:
tar -cvf archive_name.tar file1 file2 directory1 directory2
Let's break down the command options:
-c
: Create a new archive.
-v
: Display the progress of the archiving process (verbose mode).
-f
: Specify the name of the output archive file.
For example, to create a tarball named documents.tar
that includes the files file1.txt
, file2.txt
, and the directory directory1
, you would run:
tar -cvf documents.tar file1.txt file2.txt directory1
This command will create the documents.tar
file in the current directory, containing the specified files and directories.
Compressing Tarballs
You can further compress the tarball using various compression formats, such as Gzip or Bzip2. To create a Gzip-compressed tarball, you can use the following command:
tar -czf archive_name.tar.gz file1 file2 directory1 directory2
The -z
option tells tar
to use Gzip compression.
Similarly, to create a Bzip2-compressed tarball, you can use the -j
option:
tar -cjf archive_name.tar.bz2 file1 file2 directory1 directory2
The compressed tarballs will have the extensions .tar.gz
and .tar.bz2
, respectively.
To extract the contents of a tarball, you can use the following command:
tar -xvf archive_name.tar
The -x
option tells tar
to extract the files from the archive.
If the tarball is compressed, you'll need to specify the appropriate decompression option:
- For Gzip-compressed tarballs:
tar -xzf archive_name.tar.gz
- For Bzip2-compressed tarballs:
tar -xjf archive_name.tar.bz2
These commands will extract the contents of the tarball, preserving the original file and directory structure.