Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Linux tar Command
The tar command in Linux is one of the most essential commands for file management and archiving. Short for Tape Archive, it creates and extracts archive files ? compressed files containing one or more files bundled together for easier storage, backup, and portability. This guide demonstrates how to create, list, extract, and modify tar archives with practical examples.
Syntax
The basic syntax of the tar command is
tar [options] [archive-file] [files or directories]
Common Options
| Option | Description |
|---|---|
-c |
Create a new archive |
-x |
Extract files from archive |
-f |
Specify archive filename |
-v |
Verbose output (show progress) |
-t |
List contents of archive |
-z |
Use gzip compression (.tar.gz) |
-j |
Use bzip2 compression (.tar.bz2) |
-r |
Append files to existing archive |
-C |
Extract to specified directory |
Creating Archives
Basic Archive (Uncompressed)
tar -cvf documents.tar file1.txt file2.txt file3.txt
Gzip Compressed Archive
tar -czvf documents.tar.gz file1.txt file2.txt file3.txt
Bzip2 Compressed Archive
tar -cjvf documents.tar.bz2 file1.txt file2.txt file3.txt
Archive Entire Directory
tar -czvf backup.tar.gz /home/user/documents/
Listing Archive Contents
View files inside an archive without extracting
tar -tf documents.tar.gz
For detailed listing with file permissions and sizes
tar -tvf documents.tar.gz
Extracting Archives
Extract to Current Directory
tar -xvf documents.tar.gz
Extract to Specific Directory
tar -xvf documents.tar.gz -C /tmp/extracted/
Extract Specific Files
tar -xvf documents.tar.gz file1.txt file2.txt
Modifying Archives
Add Files to Existing Archive
tar -rvf documents.tar newfile.txt
Note: You can only append to uncompressed .tar files, not compressed ones.
Remove Files from Archive
tar --delete -f documents.tar unwanted.txt
Practical Examples
System Backup
tar -czvf system_backup_$(date +%Y%m%d).tar.gz /etc /home /var/log
Extract and Preserve Permissions
tar -xpvf backup.tar.gz
Create Archive Excluding Certain Files
tar -czvf project.tar.gz --exclude='*.log' --exclude='node_modules' /path/to/project/
Archive Formats Comparison
| Format | Extension | Compression | Speed | Size |
|---|---|---|---|---|
| tar | .tar | None | Fastest | Largest |
| gzip | .tar.gz/.tgz | Good | Fast | Medium |
| bzip2 | .tar.bz2 | Better | Slower | Smaller |
| xz | .tar.xz | Best | Slowest | Smallest |
Conclusion
The tar command is a versatile tool essential for Linux file management, offering flexible options for creating, extracting, and modifying archives. Understanding its syntax and compression options enables efficient file backup, distribution, and storage management in Linux environments.
