Daily Linux Command: Tar

<span>tar</span> is a very commonly used command in Linux for packaging and compressing files. It is an abbreviation for tape archive, originally used for tape backups, and is now widely used for file archiving and compression.

📌 Basic Syntax

tar [options] [archive file] [files or directories to package]

✅ Common Examples and Explanations

1. Package a directory (without compression)

tar -cvf archive.tar directory/
  • <span>-c</span>: Create a new archive file.
  • <span>-v</span>: Display file information during the packaging process (verbose).
  • <span>-f</span>: Specify the archive file name (must be followed by the file name).

Generates an uncompressed <span>.tar</span> file.

2. Package and compress with gzip

tar -czvf archive.tar.gz directory/
  • <span>-z</span>: Use gzip compression.

Generates a compressed package in <span>.tar.gz</span> or <span>.tgz</span> format.

3. Package and compress with bzip2

tar -cjvf archive.tar.bz2 directory/
  • <span>-j</span>: Use bzip2 compression.

Generates a compressed package in <span>.tar.bz2</span> format, which has a higher compression ratio than gzip but is slower.

4. Package and compress with xz (highest compression ratio)

tar -cJvf archive.tar.xz directory/
  • <span>-J</span>: Use xz compression.

<span>.tar.xz</span> format has the highest compression ratio, suitable for distributing large files.

5. Extract tar.gz files

tar -xzvf archive.tar.gz
  • <span>-x</span>: Extract files.
  • <span>-z</span>: Use gzip for extraction.
  • <span>-v</span>: Display the process.
  • <span>-f</span>: Specify the file name.

6. Extract tar.bz2 files

tar -xjvf archive.tar.bz2

7. Extract tar.xz files

tar -xJvf archive.tar.xz

8. View contents of a tar package (without extracting)

tar -tvf archive.tar
  • <span>-t</span>: List the contents of the archive.

🧠 Tips

  • If you want to compress faster (sacrificing compression ratio): use <span>gzip</span>.
  • If you want a smaller size: use <span>xz</span>.
  • If you want to compress a <span>.tar</span> file, you can first package it and then use <span>gzip</span>:
tar -cvf archive.tar dir/
gzip archive.tar
# Results in archive.tar.gz

📋 Summary of Common Options

Option Meaning
<span>-c</span> Create a new archive file
<span>-x</span> Extract the archive file
<span>-t</span> List the contents of the archive
<span>-v</span> Display the processing steps
<span>-f</span> Specify the archive file name
<span>-z</span> Use gzip for compression/extraction
<span>-j</span> Use bzip2 for compression/extraction
<span>-J</span> Use xz for compression/extraction

Leave a Comment