Compress a Directory or a Single File

Using the following command we can compress a directory ora single file on a Linux machine or on a Ubuntu Machine.

tar -czvf new-archive-file-or-directory-name.tar.gz path-to-directory-or-file

meaning of -czvf

  • -c: Create an archive.
  • -z: Compress the archive with gzip.
  • -v: Display progress in the terminal while creating, also known as “verbose” mode. v is optional.
  • -f: Allows you to specify the filename of the archive.

Compress Multiple Directory or Files at once

You can add up the path-to-directory-or-file with a space and continue in the end as below

 

tar -czvf archive.tar.gz /home/user/Downloads /usr/local/var file.txt

Excluding a directory or a file

If we want to compress the entire directory but excluding a file or a directory we can use –exclude as below

tar -czvf archive.tar.gz /home/user --exclude=/home/user/Downloads

We can also use –exclude with wild cards like below

tar -czvf archive.tar.gz /home/user --exclude=*.jpg

Compressing with bzip2 

Gzip is most frequently used as it is faster but the size of the compressed file is some what bigger but BZip2 is slow but the compressed file is smaller then the previous. The only change in the command is replacing z with j as below

tar -cjvf archive.tar.bz2 /home/user

 

Extracting an Archive

For extracting the files the command is same with a replacement of -x to -c as below

tar -xzvf archive.tar.gz

We can also extract the content of archive to a specific directory by using -C as below

tar -xzvf archive.tar.gz -C /tmp

LEAVE A REPLY

Please enter your comment!
Please enter your name here