1.11 Compression and Decompression
tar — Tape Archive Utility
Format:
tar [options] archive_name [files_or_directories]
The typical structural arrangement is:
tar -options archive_file targets_to_archive
Common Options:
-
-c: Create a new archive.
-
-x: Extract files from an archive.
-
-t: List the contents of an archive (table of contents).
-
-r: Append files to the end of an archive.
-
-u: Only append files that are newer than the copy in the archive.
-
-f: Use archive file (mandatory). The -f option must be followed immediately by the archive file name.
| Option | Compression Method | Standard Extension |
|---|---|---|
| -z | gzip | .tar.gz |
| -j | bzip2 | .tar.bz2 |
| -J | xz | .tar.xz |
| -a | Auto-detect | based on Automatic extension |
Examples:
$ tar -cvf archive.tar dir/ # Create a tar archive (uncompressed)
$ tar -czvf archive.tar.gz dir/ # Create a gzip compressed tar archive
$ tar -cJvf archive.tar.xz dir/ # Create an xz compressed tar archive (high compression ratio)
$ tar -xvf archive.tar # Extract an uncompressed tar archive
$ tar -xzvf archive.tar.gz # Extract a gzip compressed tar archive
$ tar -xzvf archive.tar.gz -C /target/path # Extract to a designated target path
$ tar -tvf archive.tar # List archive contents verbosely
Common Control Options:
| Option | Architectural Meaning / Function |
|---|---|
| -v | Verbose mode (display file progression details). |
| -C | Change to specified directory before、executing operations. |
| --exclude | Exclude files matching a specified pattern. |
| -p | Preserve original file permissions and |
| --strip-components=n | Strip n leading components from file names on extraction. |
Advanced Practical Invocations:
$ tar -czvf backup.tar.gz /project --exclude="*.log" # Exclude file pattern example
$ tar -xvf archive.tar file.txt # Extract a specific file from archive
$ tar -czvf backup.tar.gz . # Archive the current working directory
Standard Archiving and Extraction Examples:
$ tar -xvf file.tar
$ tar -czvf file.tar.gz dir
$ tar -xzvf file.tar.gz
$ zip -r file.zip dir
$ unzip file.zip