The tar command in Linux is used to bundle up multiple files and/or directories. It’s similar to the zip command. However, zip files are compressed by definition; tar files can be compressed, but don’t have to be.
Table of Contents
How to Use tar command on Linux
The basic command for creating tar.gz files is as below:
$ tar -czvf archivename.tar.gz filename…
- -c is tells tar to create a new archive.
- -z is sets the compression method to gzip.
- -f archive-name.tar.gz specifies the name of archive.
- filename… represents a list of files and directories to be added into the archive with space-separated. (for example :- filename1 filename2 )
The basic command for extracting a tar.gz files is as below:
Get Your Free Linux training!
Join our free Linux training and discover the power of open-source technology. Enhance your skills and boost your career! Learn Linux for Free!$ tar -xzvf archivename.tar.gz
Create a tar Archive
As an example, we create a Tar File named “example.tar.gz” with “filename1” and “filename2“
$ tar -czvf example.tar.gz filename1 filename2
The above command doesn’t show any output on success. So if we want verify that the archive is created or not, then list the directory contents with ls command.
If you wish to create the tar.gz inside a directory, then type full path to the archive file same as below:
$ tar -czvf /home/user/example.tar.gz filename1 filename2
Extract a tar Archive
The following command will extract the contents of archive.tar.gz to the current directory.
tar -xzvf archive.tar.gz
We may want to extract the contents of the archive to a specific directory. We can do this by appending the -C switch to the end of the command. For example, the following command will extract the contents of the archive.tar.gz file to the /home directory.
tar -xzvf archive.tar.gz -C /home
view the contents of a tar archive
we might need to view the contents of an archive without actually extracting it. we can do this with the -t flag.
tar -tvf logs_archive.tar.gz
In this command, -t flag specifies that we need to only view the contents of the archive. -f specifies the filename and -v displays the detailed contents.
search compressed log files in a tar archive
we might still need to access certain files once they’re archived. Luckily, there is a method we can use to search and view compressed log files without decompressing them and compromising disk space.
The command we can use to search in compressed files is zgrep:
We can search for a string in an archive using the below command:
zgrep -Hna 'string-to-search' compressedFile.tar.gz
Let’s briefly look at the flags.
- -H lists the file name that contains the match.
- -n displays the line number that contains the matched string.
- -a treats all files as text files.