The gzip
command in Linux comes as part of the GNU Core-utilities package and is used to compress or decompress files.
The gzip
command has many functionalities, which we can access by using the right flag.
In this shot, we will review some of the most widely used flags for gzip
.
The gzip
command is used without any flags to compress one or more files. The filenames are sent as arguments to the gzip
command.
Note that the original file is deleted, but the timestamp, mode and ownership, and name of the old file are preserved in the compressed file.
If you do not want the original file to be deleted, use the -k
flag.
The -v
flag stands for verbose and works the same way as gzip
without any flags. The only difference is that it generates a report of the compressed and uncompressed file, which contains the percentage reduction of each processed file.
Multiple files may be compressed by giving multiple file names as arguments to the gzip
command.
To compress the files in a directory or folder, its path from the current directory is sent as an argument to the gzip
command along with the -r
flag, which recursively navigates its way up through the entire directory and compresses all the files in it.
The gzip
command allows the user to set a compression level ranging from 1 to 9. 1 provides the minimum amount of compression but the fastest speed.On the other hand, 9 is used to maximize compression but at the cost of slow speed. Level 6 balances the two trade-offs well.
The gzip
command is used with the -d
flag to decompress gz
archives. The name of the archive is sent as an argument after the -d
flag. The archive itself is lost.
To preserve the archive that is decompressed, use the dk
flag instead.
To decompress all the compressed files or folders in a directory, use the -dr
flag and send the path to this directory as the argument.
The -h
flag is used to open the manual page for gzip, which contains additional information about it.
The
gzip
command can only compress the files inside a folder on Linux and not the folder itself. The-z
flag of tar is used for this purpose!
In the example below, we first use the ls
command to list down all the folders and files in the current directory.
We create a new text file using the echo
command and compress it using the -v
flag, which compresses the text file and states the compression ratio. We use the ls
command to see that we now have the compressed text file.