Compress file or directory using the GZIP command in Linux

Home > Search > Linux commands

The gzip command can be used to compress files or directories. Let's take an example where /home/john.doe contains a few files and directories, where example.file is 672 bytes.

~]# ll /home/john.doe
-rw-r--r-- john.doe john.doe 672 Jan 01 :17:16 example.txt


The gzip command can be used to compress example.txt.

~]# gzip example.txt


This will create a new file named example.txt.gz. In this example, the compressed file is 52 bytes.

~]# ll /home/john.doe
-rw-r--r-- john.doe john.doe 52 Jan 01 :17:16 example.txt.gz


Compress every file in a directory

The -r or --recursive option can be used to compress every file at or below a directory. This does not create one .gz file that contains every file in the directory. Instead, this creates individual .gz files for each file in the directory. If you want to create one file that contains every file in the directory, you would create a tar archive.

In this example, every file at and below /home/john.doe will be compressed.

~]# gzip -r /home/john.doe



When manually issuing the gzip command, you may be prompted "do you want to overwrite". If you are using gzip in a script, you may want to set a default action, such as "y" to overwrite or "n" to not overwrite. In this example, the default action will be "n" to not overwrite.

yes n | gzip example.txt


Compression level

The -1 through -9 options can be used to select the compression level. -1 will have the least compression, but will be the fastest to compress. -9 will have the most compression, but will be the slowest to compress. In this example, example.file is compressed with the most compression. If the compression level is not specified, the default compression level used is -6.

~]# gzip -9 example.txt



The -l or --list option can be used to view statistics of a compressed gzip file. The -l option will display the size of the uncompressed file, the size of the compressed file, the compression percentage, and the name of the uncompressed file.

~]# gzip -l /home/john.doe/example.txt.gz
compressed  uncompressed  ratio  uncompressed_name
        52           672  96.9%       example.txt



The -d, --decompress, or --uncompress option can be used to uncompress a gzip compressed file. In this example, example.txt.gz is uncompressed. Similarly, the gunzip command can also be used to decompress a gzip compressed file.

~]# gzip -d example.txt.gz


Add a Comment

We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.

Please enter in the box below so that we can be sure you are a human.