Gzip and Keep Original File in Linux

gzip and keep the original file in linux

Gzip command by default delete the original file and replace it with a new compressed file with .gz extension. In this article, I am going to show you how to gzip file and keep the original ones intact.

Previously, we have seen how you can compress files using the zip command in a Linux system.  Additionally,  we have also seen how you can use the gzip command to compress and decompress files.

Gzip and keep the original file

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

Method 1: Using -k option

$ sudo gzip -k picture.img

or

$ sudo gzip --keep picture.img
gzip-k-keep-original

gzip keeping the original file

Method 2: Using -c option

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

gzip c option to keep original file

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

Method 3: Using shell redirections

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

gzip shell redirection

Note: You might have noticed I have used sudo sh -c command, this is because redirection is done by shell and sudo don't have permission

To gzip all files

To gzip all files in the current folder and subfolders, use:

$ sudo gzip -kr .

gzip all files

To gzip all files and subfolders

Unlike gzip command, tar command by default will keep the original directories or files, use:

$ sudo tar -zcvf compressednewfile1.tar.gz directorytocompress

or

$ sudo tar -zcvf allfilesdirectories.tar.gz *

Choose a selected number of directories to gzip:

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

Conclusion

As you have seen in this guide, gzip allows you not only to compress a file but also gives you the privilege to retain the original file after compression. For users who prefer keeping the original files, this comes as a very handy method and saves you time and energy. We do hope that you found this helpful. Your feedback is much appreciated.

Jamie Arthur 5:12 am

Comments

Your email address will not be published. Required fields are marked *