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.
In addition, we also saw how to use the gzip command to compress and decompress files:
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
$ 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
$ sudo tar -zcvf allfilesdirectories.tar.gz *
Select the required number of directories to compress:
$ sudo tar -zcvf directory1and2.tar.gz dir1 dir2
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.