In this tutorial, How do I use the tar command the compress and extract files and folders in Linux? Linux the essential for DevOps Roles.
The tar
command in Linux is used for creating and manipulating tar archives, which are commonly used for bundling multiple files and directories into a single file. Here are a few examples of how to use the tar
command.
Table of Contents
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 compress “xz” by using the -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 is 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 the 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
Through the article, you can use tar command examples in Linux as above. These are just a few examples of how to use the tar
command in Linux. The tar
command offers many other options and functionalities, so you can refer to the command’s manual (man tar
) for more detailed information and usage examples. I hope will this your helpful. Thank you for reading the DevopsRoles page!