Archive, backup, compress, unpack, and uncompress files

Compress and entire directory or a single file

This command will compress the file or directory on /path/to/directory-or-file into a file called name-of-new-archive.tar.gz

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

Options are

  • c : means create
  • z : define a gz file type
  • v : means verbose
  • f : allows to specify the file name of the archive

Compress many directories or files

Sample

$ tar -czvf archive.tar.gz /home/abernal/files /home/pbernal/files /home/users/lists.txt

Exclude directories and files

If we wanted to backup a directory but exclude given files or directories within it, we shall use the --exclude option

Sample

$ tar -czvf new-archive.tar.gz /home/abernal --exclude=/home/abernal/videos --exclude=*.mp4 --exclude=/home/abernal/file_to_be_excluded.txt

Using bzip2 compression instead

In order to use bzip2 we use the "j" parameter for tar like this

$ tar -cjvf new-archive.tar.bz2 /home/abernal/files

Extract an archive

Sample

$ tar -xgvf archive.tar.gz

This command will extract the content of archive.tar.gz in the current directory.

If we want to extract the content of a .tar.gz file into a given directory we can use the -C option, for example

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