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
Options
-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
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-folder/ ./tar-folder/folder2/
Conclusion
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!