tar command examples in linux

In this tutorial, How do I use tar command the compress and extract files and folder in Linux? Linux the essential for DevOps Roles.

The syntax tar command

tar [Options] your_tar_name.tar source_tar


-c –create Create a new archive.
-x –extract Extract files from an archive.
-t –list List the contents of an archive.
-f –file=ARCHIVE Use archive file or directories ARCHIVE.
-v –verbose Verbosely list files processed.
-a –auto-compress Use archive suffix to determine the compression program.
-j –bzip2 Filter the archive through bzip2.
-J –xz Filter the archive through xz.
-z –gzip Filter the archive through gzip.

For example tar command examples, compress a directory.

Creating an archive of a directory as command below

[huupv@huupv devopsroles]$ tar -cvf folder.tar folder

The archiving a folder compressed “gzip” you can use -z option.

[huupv@huupv devopsroles]$ tar -czf folder.tar.gz folder

You can compress the archive with “bzip2” by using -j option

[huupv@huupv devopsroles]$ tar -cjf folder.tar.bz2 folder

Or the compress “xz” by using -J option.

[huupv@huupv devopsroles]$ tar -cJf folder.tar.xz folder

For example, Extract a directory from an archive

To extract a directory from an archive in the current location

[huupv@huupv devopsroles]$ tar -xvf folder.tar

Or to extract a directory from an archive to a specific “your_folder”.

[huupv@huupv devopsroles]$ tar -xvf  folder.tar -C ./directory/your_folder

For example list archive content

Listing content as command below

[huupv@huupv devopsroles]$ tar -tvf folder.tar

For listing the content of a tar.gz archive

[huupv@huupv devopsroles]$ tar -tzvf folder.tar.gz

Compress and exclude one or multiple directories

This my folder tree

[huupv@huupv devopsroles]$ tree tar-folder
├── folder1
├── folder2
└── folder3

3 directories, 0 files

You can exclude one or several folders “–exclude” option as command below

[huupv@huupv devopsroles]$ tar --exclude='./tar-folder/folder1' --exclude='./tar-folder/folder3' -cvf my-archive.tar ./tar-folder

The screen output terminal


tar command examples in linux


Thought the article, you can use tar command examples in Linux as above. I hope will this your helpful. Thank you for reading the DevopsRoles page!

About HuuPV

My name is Huu. I love technology and especially Devops Skill such as Docker, vagrant, git so forth. I likes open-sources. so I created DevopsRoles.com site to share the knowledge that I have learned. My Job: IT system administrator. Hobbies: summoners war game, gossip.
View all posts by HuuPV →

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.