๐Ÿ“ฆ 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.