Tar is a popular archiving format on linux, most time distress are compressed in tar to deliver packages and updates.
Tar is also common in file sharing online. Everybody is used to compressing and extracting files using tar but always confuse with options should be passed based on file extension.
Lets see how to compress and extract files using tat in linux.
All linux distress comes with the tar tool for managing tar archives.
Create and manage tar files
Lets create a directory as follows.
And lets create a text file using nano editor in the directory
And save the file using CTRL + X in nano editor.
Now lets compress the directory /usr/src/test including the text file in it.
The tar will use various compression algorithms to compress the files. It’s a common practice that the compression algorithm dictates the output file name.
Run the following command to create a tar archive using gzip compression.
tar -cvzf test.tar.gz <source_file_directory>
In our case it will be
tar -cvzf test.tar.gz /usr/src/test
To do the same with bzip2 compression, use the following command.
tar -cvjf test.tar.bz2 <source_file_directory>
To create archive using XZ compress, run the following command.
tar -cvJf test.tar.xz <source_file_directory>
Extracting tar files
We can list all the files and directories included in the tar archive by running following command.
tar -tvf <tar_archive_file_name>
Let’s check the flags we used.
t: It is to list the contents of the archive.
v: It tells tar to show its action on console.
f: It tells tar which file to perform the action on.
Now lets extract entire archive file using tar command.
While you needed to use different commands to create different types of tar archives, we can use only a single tar command to extract all of them.
Run the following tar command to extract any valid tar archive.
If files with similar filenames exist, upon extraction, tar will overwrite the files outside the archive.
tar -xvf <tar_archive_filename>
The ‘x’ flag is used to tell the tar to extract an archive.
To prevent overwriting existing files with same names, add the ‘-k’ flow.
Now the command will look like as follows.
tar -xvkf <tar_archive_filename>
Sometimes we will not have to extract the entire tar archive extracted only to get a single file. The tar tool has such flexibility that you can extract only the specific files you need.
For this task, the tar command structure as follows. Here, replace the file name with the name of your desired file. It must match with the file name that’s inside the tar archive.
tar -xvf <tar_archive_filename> <filename>
You can add as many file names as you need as follows.
tar -xvf <tar_archive_filename> <filename1> <filename2>
Also you can extract some selected directories from the tar tar archives as follows.
tar -xvf <tar_archive_filename> <directory_name>
Similar to files, you can extract multiple directories as follows.
tar -xvf <tar_archive_filename> <directory_name1> <directory_name2> <directory_name3>