How to Compress and Extract Files Using the tar Command on Linux
Last Updated :
29 Jun, 2021
An archive is a special file that contains any number of files inside. It can be restored via special programs, for example, tar.inside.
- .tar – archive files are usually not compressed.
- .tar.gz – archive file compressed with gzip tool
- .tar.bz2 – archive file compressed with bzip2 tool
Syntax:
tar options [archive_name.tar] files_to_archive
The tar command does not create a compressed archive, instead, it uses external utilities like gzip and bzip2.
Command functionality:
Option |
Full format |
Description |
-a |
–concatenate |
Concentrate two archives |
-c |
–create |
Creating a new archive |
-d |
–diff
–delete
|
Showing the difference between archives
Delete file from the archive
|
-r |
–append |
add files at the end of the existing archive |
-t |
–list |
Show archive content |
-u |
–update |
Update an archive |
-x |
–extract |
Extract files from the archive |
Command parameters:
Parameter |
Full format |
Description |
-C dir |
–directory=DIR |
change directory before executing |
-f |
–file=ARCHIVE |
Use specified archive file |
-j |
–bzip2 |
compress using bzip2 |
-p |
–same-permissions |
Save file permissions to file |
-v |
–verbose
–total
|
Show process information
Show final result
|
-z |
–gzip |
compress using gzip |
Example of using the tar command:
1) Compress one file using the tar command:
tar -czvf one-file-compressed.tar.gz hello_world
2) Compress directory using the tar command:
tar -czvf dir-compressed.tar.gz test_directory/
3) Show the archive content:
tar -tf archive.tar.gz
4) Add content to the existing archive:
tar -rvf existing-archive-name.tar file-directory-to-compress/
5) Update content in an archive:
6) Compress with bzip2:
tar -cjvf one-file-compressed.tar.bz2 hello_world
7) Extract files from a .tar archive:
tar -xf archive.tar.gz
The same with .tar.gz and .tar.bz2
Share your thoughts in the comments
Please Login to comment...