Skip to content

πŸ“¦ Tar Command

What is tar?

tar (short for tape archive) is used to bundle multiple files into one archive file. It’s often combined with compression (like gzip) to reduce size.


Common Flags

  • -x β†’ extract files
  • -c β†’ create an archive
  • -v β†’ verbose, show progress
  • -f β†’ file name, tells tar which archive file to work on
  • -z β†’ gzip, used if the archive ends with .gz
  • -C β†’ change directory before extracting/creating

Understanding -f

  • -f means:

β€œThe next argument is the filename of the archive.”

βœ… Example:

tar -xzvf archive.tar.gz

❌ Wrong (no -f):

tar -xzv archive.tar.gz

Tar will get confused because it doesn’t know archive.tar.gz is the file to work on.

When is -f not needed?

  • Only when reading/writing via stdin/stdout (e.g., using pipes).

Example:

curl -L https://example.com/archive.tar.gz | tar -xzv

Here tar doesn’t need -f because it’s reading directly from the pipe instead of a file.

πŸ‘‰ Rule of Thumb: Always use -f when working with a local archive file.


File Types

  • .tar β†’ archive only (no compression)
  • .tar.gz or .tgz β†’ archive + gzip compression

Extracting

  • From .tar (no compression):
tar -xvf archive.tar
  • From .tar.gz:
tar -xzvf archive.tar.gz
  • Extract into a specific directory:
tar -xzvf archive.tar.gz -C /target/directory

Creating

  • Create .tar:
tar -cvf archive.tar file1 file2 dir1/
  • Create .tar.gz:
tar -czvf archive.tar.gz file1 file2 dir1/

❌ Common Mistakes

  • Wrong:
tar Cxzvf /usr/local archive.tar.gz

πŸ‘‰ C is misplaced; tar thinks it’s a file.

  • Correct:
tar -xzvf archive.tar.gz -C /usr/local

🧠 Quick Memory Trick

Think of tar as β€œaction β†’ details β†’ file β†’ where”:

-xzvf  [WHAT to extract]   -C [WHERE to put it]

🎁 Real-World Analogy

Think of tar like packing and opening gifts:

  • .tar = 🎁 A box containing multiple items (but the box is full size).
  • .tar.gz = πŸŽπŸ“¦ A box that has been vacuum-sealed (smaller size).
  • -x = You open the box.
  • -c = You pack items into the box.
  • -z = You shrink/expand the vacuum seal.
  • -f = You point to which box you’re opening.
  • -C = You decide where in the house you want to place the opened items.