Skip to content

tar & gzip example

Archive a Directory

  1. Make a directory on your system and create a text file:

    mkdir testdir && touch testdir/example.txt
    
  2. Use tar to archive the directory:

    tar -cvf testdir.tar testdir/
    
  3. Check for the newly archived tar compressed file:

    ls
    
    tesdir  testdir.tar
    

Compression with gzip

  1. Compress files in Linux using gzip:

    gzip testdir.tar
    
  2. Checking for the output file will show:

    ls
    
    testdir  testdir.tar.gz
    
  3. The chained file extension (.tar.gz) indicates that this is a compressed archive. You can see the difference in size between the two files, before and after compression:

    ls -l --block-size=KB
    
    total 9kB
    drwxrwxr-x 2 vps vps 5kB Jan 30 13:13 testdir
    -rw-rw-r-- 1 vps vps 1kB Jan 30 13:29 testdir.tar.gz
    

Extract a Tarball

Extract the directory:

tar -xzvf testdir.tar.gz
testdir/
testdir/test.txt

The flags used in these examples stand for:

  • c: Create a new archive in the form of a tar file.
  • v: Verbose flag, outputs a log after running the command.
  • z: Zips or unzips using gzip.
  • x: Extracts a file from the archive.
  • f: Defines STDOUT as the filename or uses the next parameter.

Common Options for Compressing and Archiving Files in Linux

Additional flags used with the tar command are:

Flag Function
-A Append tar files to an existing archive.
-d Show differences between an archive and a local filesystem.
-delete Delete from the archive.
-r Append files to the end of an archive.
-t List the contents of an archive.
-u Append but don’t overwrite the current archive.

These are the basics for working within the command line. Be sure to check the man pages man tar for a more detailed listing of possible flags when compressing and extracting files.

https://www.linode.com/docs/guides/archiving-and-compressing-files-with-gnu-tar-and-gnu-zip/

Feedback