The Gzip command in Linux is used for compressing and decompressing files. This command is also used as gunzip for g-un-zip i.e. to unzip a gzip archive.
It’s necessary that we compress files Expanding files is useful to open compressed files downloaded from the internet.
Using the gzip Command in Linux
Let’s understand how we can compress and decompress files using the gzip command in Linux.
1. Compress a file
Compressing a file is straightforward with gzip command. You just have to mention the name of the file along with the command.
$ gzip [filename]
You can see that the compressed file appears in the list with a .gz extension.
2. Compress multiple files
To compress multiple files, specify the name of the files with spaces in between as shown below.
$ gzip [filename1] [filename2]
We can see that both the files appear with a .gz extension. If a compressed version of a file already exists then it will ask you to overwrite.
3. Decompress a file
There are two ways to decompress a file. The first one is using a ‘d’ flag with gzip command.
$ gzip -d [filename]
We can see that the file appears in the list as without a .gz extension.
The second way is by using gunzip command.
$ gunzip [filename]
4. Keep the original file after compression
The gzip command removes the original file and only keeps the compressed file once the operations are completed. If you want to keep the original file as well use -k flag.
$ gzip -k [filename]
We can see that both the original and compressed file are present in the list.
Using the Gzip Command to Retrieve Information from Compressed Files
You may also need to retrieve compression and compressed file-related information from the gzip archive. You can obviously make use of the ls command to get the file size but that won’t tell you the compression ratio, and the size before and after compression.
That’s where gzip’s built in functionality comes into place!
1. Get information about the compression
To gain information about the compression like the compression ratio use –l flag.
$ gzip -l [filename]
Note that the filename is that of an already compressed file. It provides four fields of information about the compression performed.
- Compressed size
- Uncompressed size
- Uncompressed filename
2. Display contents of the file
To display the contents of the file without decompressing, use the -c flag along with gunzip command.
gunzip -c [filename]
In this tutorial we saw how gzip and gunzip commends are useful in linux for compression and expanding of files. Compressing of files is common before attaching them in mails.