Using tar in Linux
The tar command in Linux is used to create, maintain, modify, and extract files from a tar archive. While Linux doesn't require filename extensions, it's a common convention to use the .tar suffix for tar files for convenience. Compressed tar archives usually end in a .tar.gz, .tar.bz2, or .tar.xz suffix to make it easier to know how the file is compressed.Creating a Tar File
Example 1: Creating a Tar File with a Couple of Files in the Same Directory
To create a tar file with just a couple of files in the same directory, use the following command:
Code:
tar -cvf archive.tar file1.txt file2.txt
Example 2: Using Wildcards to Archive a Specific File Type
To archive all files of a specific type (e.g., .txt files) in a directory, use:
Code:
tar -cvf textfiles.tar *.txt
Example 3: Including Everything Beneath a Directory
To include everything beneath a directory (e.g., mydir), use:
Code:
tar -cvf mydir.tar mydir/
Extracting a Tar File Archive
To extract a tar file archive, use the following command:
Code:
tar -xvf archive.tar
Handling Soft Links and Hard Links
Soft links (symbolic links) and hard links can cause problems when creating tar files. Soft links point to the original file, and if the original file is moved or deleted, the link becomes broken. Hard links, on the other hand, point directly to the data on the disk, and multiple hard links to the same file share the same data blocks.When creating a tar archive, you can use the -h option to follow symbolic links and archive the files they point to:
Code:
tar -cvhf archive.tar symlink
Reasons to Create a Tar File
- Backup: Tar files are commonly used for backing up data.
- Distribution: Tar files can be used to distribute multiple files as a single package.
- Compression: Tar files can be compressed to save space.
- Historical Context: In the early days of Linux, before the advent of .deb and .rpm packages, tar.gz files were the common way to install certain programs and applications.
Compressing and Decompressing Tar Files
Compression Methods
- gzip: Compresses faster but may not achieve the smallest file size.
- bzip2: Compresses slower but achieves a smaller file size.
- xz: Compresses even slower but achieves the smallest file size.
Example Commands
To create a compressed tar file using gzip:
Code:
tar -cvzf archive.tar.gz mydir/
To extract a gzip-compressed tar file:
Code:
tar -xvzf archive.tar.gz
To create a compressed tar file using bzip2:
Code:
tar -cvjf archive.tar.bz2 mydir/
To extract a bzip2-compressed tar file:
Code:
tar -xvjf archive.tar.bz2
To create a compressed tar file using xz:
Code:
tar -cvJf archive.tar.xz mydir/
To extract an xz-compressed tar file:
Code:
tar -xvJf archive.tar.xz