🐧 How to Gzip and Save Source File on Linux

The Gzip command, by default, removes the original file and replaces it with a new compressed file with a .gz extension.

In this article, I will show you how to compress a file using gzip and keep the original files intact.

We have previously seen how you can compress files using the zip command on Linux.

🐧 How to create and unzip Zip files to a specific directory in Linux and Windows

In addition, we also saw how to use the gzip command to compress and decompress files:

How to gzip all or specific files in Linux

🗃️ How to extract a specific file from a tar archive

How to compress a file with Gzip and keep the original file

We can use three options to keep the original file when using gzip:

Method 1: using the -k option

$ sudo gzip -k picture.img

or

$ sudo gzip --keep picture.img

Method 2: using the -c option

$ sudo gzip -c picture.img > picture.img.gz

For the gunzip command, you can use the same -c option to keep the original file.

Method 3: using shell redirection

$ sudo gzip < picture.img > picture.img.gz

How to compress all files

To compress all files in the current folder and subfolders use:

$ sudo gzip -kr .

How to compress all files and subfolders

Unlike the gzip command, the tar command by default preserves the original directories or files, use this option:

$ sudo tar -zcvf compressednewfile1.tar.gz directorytocompress

or

$ sudo tar -zcvf allfilesdirectories.tar.gz *

Select the required number of directories to compress:

$ sudo tar -zcvf directory1and2.tar.gz dir1 dir2

Conclusion

As you saw in this tutorial, gzip not only allows you to compress a file, but also gives you the right to keep the original file after compression. For users who prefer to keep the original files, this is a very convenient method that will save you time and effort.

Sidebar