How to create tar.gz file in Linux using command line

02 Aug 2024 - 2 min read
How to create tar.gz file in Linux using command line

The tar command in Linux and Unix-like operating systems is used to create compressed and uncompressed archive files. It is a versatile utility that can combine multiple files and directories into a single archive file, which can then be compressed to save space or to make it easier to transfer. Below, I’ll explain how to use tar to compress and uncompress files with examples.

Table of Contents

Basic tar Commands

Compress (Create Archive)

The basic syntax to create a tar.gz archive is:

Terminal
tar -czvf archive.tar.gz directory

Uncompress (Extract Archive)

To extract an archive, use the following syntax:

Terminal
tar -xzvf archive.tar.gz

Common Use Cases

Archive and Compress Multiple Directories:

Terminal
tar -cvzf archive.tar.gz /dir1 /dir2 /dir3

This command archives and compresses multiple directories into a single file.

List the Contents of an Archive:

Terminal
tar -tzvf archive.tar.gz

This will list the contents of the specified archive without extracting them.

Add Files to an Existing Archive:

Terminal
tar -rzvf archive.tar.gz new-file

Adds a new file to an existing archive.

Exclude Specific Files/Directories:

Terminal
tar --exclude='*.log' -cvzf archive.tar.gz directory

Excludes all .log files from the archive.

Summary Table

OperationCommand Example
Create Uncompressed Archivetar -cvf archive.tar /path/to/directory
Create Gzip Compressed Archivetar -cvzf archive.tar.gz /path/to/directory
Create Bzip2 Compressed Archivetar -cvjf archive.tar.bz2 /path/to/directory
Create XZ Compressed Archivetar -cvJf archive.tar.xz /path/to/directory
Extract Uncompressed Archivetar -xvf archive.tar
Extract Gzip Compressed Archivetar -xvzf archive.tar.gz
Extract Bzip2 Compressed Archivetar -xvjf archive.tar.bz2
Extract XZ Compressed Archivetar -xvJf archive.tar.xz
Extract to Specific Directorytar -xvzf archive.tar.gz -C /path/to/destination
List Contents of Archivetar -tvf archive.tar
Add Files to Existing Archivetar -rvf archive.tar new-file
Exclude Files/Directoriestar --exclude='*.log' -cvzf archive.tar.gz /path

These commands provide a comprehensive guide to using tar for compressing and uncompressing files and directories. With tar, you can easily manage file archives and compress them for efficient storage and transfer.

ThinhHV

About ThinhHV

DevOps • Fullstack Developer • Amateur Photographer