When working in a Linux terminal environment, you will frequently encounter compressed archives ending in .tar.gz or .tgz. These files are the standard method for distributing software source code, backup archives, and large datasets in the open-source ecosystem.
Before you blindly extract an archive to your local directory (which could potentially overwrite existing files or create a massive mess of thousands of nested folders), it is a best practice to peek inside the archive first. Fortunately, you can view the complete contents of a .tar.gz file directly in the terminal without extracting a single byte.
Using the ‘tar’ Command to List Contents
The standard Linux tar command includes a built-in function specifically for listing the contents of an archive. You simply need to use the -t (list) flag.
Open your terminal and run the following command, replacing filename.tar.gz with your actual file:
tar -tzf filename.tar.gz
Here is exactly what these flags are doing:
- -t (list): Instructs tar to list the contents rather than extract or create an archive.
- -z (gzip): Instructs tar to filter the archive through gzip to decompress it on the fly.
- -f (file): Specifies the filename of the archive you are targeting.
How to Format the Output for Better Readability
If the archive contains thousands of files, running the standard command will flood your terminal screen, making it impossible to read. You can solve this by piping the output into the less command.
tar -tzf filename.tar.gz | less
This allows you to scroll through the file list line by line using your arrow keys. Press q to quit when you are finished.
Viewing Detailed File Permissions
If you need more information than just the filenames, you can add the -v (verbose) flag. This will display the output in a format very similar to the ls -l command, showing file permissions, ownership, file sizes, and modification dates.
tar -tvzf filename.tar.gz
Searching for a Specific File Inside the Archive
If you know the archive contains a specific configuration file but you do not want to scroll through a massive list to find its exact path, you can combine the tar command with grep.
For example, if you want to see if an archive contains a file named config.php, you would run:
tar -tzf filename.tar.gz | grep "config.php"
If the file exists inside the archive, the terminal will print its exact directory path. If it does not exist, the command will return nothing.
Extracting Only One Specific File
Once you have viewed the contents and found the exact path of the file you need, you do not have to extract the entire archive. You can instruct tar to extract only that specific file.
To do this, use the extract (-x) flag followed by the exact path you found in the previous step:
tar -xzf filename.tar.gz path/to/specific/config.php
By mastering these simple flags, you can safely navigate, inspect, and manage compressed archives on your Linux server without cluttering your filesystem.