Now that we know how to create archives and view their contents, let's learn how to extract files from an archive. This is useful when you need to restore files from a backup or when you receive an archive from someone else.
To demonstrate this, let's first simulate a scenario where our original directory structure is lost. We'll remove the document_library directory:
rm -rf ~/project/document_library
The rm command removes files and directories, and the -rf options tell it to operate recursively and force removal without prompting for confirmation. Be careful when using this command in real-world scenarios, as it permanently deletes files.
Let's verify that the directory is gone:
ls -la ~/project
You should not see document_library in the listing, but you should still see your documents_archive.tar.gz file.
Now, let's extract the archive to restore our files. The basic syntax for extracting with tar is:
tar [options] [archive-name]
Common extraction options include:
-x: Extract files from an archive
-z: Decompress using gzip
-v: Verbose mode (show progress)
-f: Specify the filename of the archive
-C: Change to the specified directory before extracting
Let's extract our archive:
tar -xzvf ~/project/documents_archive.tar.gz -C ~/project
In this command:
-x tells tar to extract files
-z tells tar to decompress the gzipped archive
-v enables verbose mode, showing the files being extracted
-f ~/project/documents_archive.tar.gz specifies the archive file
-C ~/project tells tar to extract the files to the ~/project directory
You should see output listing all the files being extracted, similar to what you saw when creating the archive.
Let's verify that our directory structure has been restored:
ls -R ~/project/document_library
You should see the same directory structure and files that we originally created:
/home/labex/project/document_library:
references reports specifications
/home/labex/project/document_library/references:
guide.txt handbook.txt manual.txt
/home/labex/project/document_library/reports:
annual.txt monthly.txt quarterly.txt
/home/labex/project/document_library/specifications:
product.txt service.txt system.txt
If you only want to extract specific files from an archive, you can specify their paths after the archive name. For example, to extract only the reports directory:
mkdir -p ~/project/extracted_reports
tar -xzvf ~/project/documents_archive.tar.gz -C ~/project/extracted_reports document_library/reports
This will extract only the reports directory and its contents to the extracted_reports directory.
Congratulations! You've successfully learned how to extract files from an archive using the tar command. This skill is essential for restoring backups, installing software from source, and many other Linux operations.