Gzip which stands for "GNU zip" is a file compression tool used to reduce the size of files, making them easier and faster to transfer over networks or devices. Gzip is commonly used in Unix-based systems but is supported across many platforms. It is especially popular for compressing web files like HTML, CSS, and JavaScript to improve website performance by reducing load times. Unlike other archive tools like ZIP, gzip compresses a single file rather than combining multiple files into an archive.
In this blog, we will list some of the most common flags for gzip and give you a couple of examples of working with the program.
Gzip flags
Gzip uses the following syntax:
gzip [flag] [file]
-f : Forcefully compress a file even if a compressed version with the same name already exists.
-k : Keeps the original file after compression.
-r : Recursively compress all files in a folder and its subfolders.
-v : Displays the name and percentage compression for the compressed or decompressed files.
-[1-9] : adjusts the compression level used. 1 being the fastest but least compressed and 9 being the slowest but most compressed. The default is 6
-d : Decompresses a file
Compressing files
To compress a file using gzip use the following command
gzip [filename]
This will compress the file and delete the original file
If you wish to keep the original file use the -k flag and the command will look like this
gzip -k [filename]
Decompressing files
To decompress a file use the -d flag
gzip -d filename
Alternatively, you can use the command gunzip without the need for a flag.
Verbose mode
If you need to check the percentage of compression or decompression of a file you can use the -v flag:
gzip -v file1
Example output
file1: 50.3% -- replaced with file1.gz
Recursive compression
If you want to compress a whole directory of files you can do so with the -r flag. Keep in mind that this won't create an archive but will compress each file separately.
gzip -rv /var/log
Example output:
/var/log/syslog: 75.2% -- replaced with /var/log/syslog.gz
/var/log/auth.log: 60.5% -- replaced with /var/log/auth.log.gz
/var/log/kern.log: 65.8% -- replaced with /var/log/kern.log.gz
/var/log/dmesg: 72.9% -- replaced with /var/log/dmesg.gz
/var/log/apache2/access.log: 81.0% -- replaced with /var/log/apache2/access.log.gz
/var/log/apache2/error.log: 77.3% -- replaced with /var/log/apache2/error.log.gz