≡ Menu

How to gzip and keep original file on Unix or Linux command line

I would like to compress a log file using gzip Unix command line utility, and I would also like to keep the original file. However, when I use the gzip my-app.log command, results in modifying my log file and renaming it my-app.log.gz. How do I force the gzip command to keep original file while maintaining the original file on Linux or Unix-like system?

The gzip program compresses and decompresses files on Unix like system. You need to pass the -c or --stdout, or --to-stdout option to the gzip command. This option specifies that output will go to the standard output stream, leaving original files intact.

Syntax: To keep original file while using gzip

The options are as follows:
gzip -c input.file > output.file.gz
If no files are specified and in direction used, gzip will compress from standard input, or decompress to standard output. So one can use the following syntax:
gzip < input.file > output.file.gz
Or pass the -k/--keep to the gzip command to leep (don’t delete) input files during compression or decompression:
gzip -k input.file
gzip --keep input.file

Examples

Let us tell gzip command to keep original file called Friday-Comic.jpg :
$ ls -lh Friday-Comic.jpg
Gzip and create a new file called Friday-Comic-1.jpg.gz:
$ gzip -c Friday-Comic.jpg > Friday-Comic-1.jpg.gz
$ ls -lh Friday-Comic-1.jpg.gz

Gzip and create a new file called Friday-Comic-1.jpg.gz using shell redirection:
$ gzip < Friday-Comic.jpg > Friday-Comic-2.jpg.gz
$ ls -lh Friday-Comic*

Sample outputs:

Fig.01: Tell gzip command to keep original file on Unix or Linux system

Fig.01: Tell gzip command to keep original file on Unix or Linux system

Share this tutorial on:
{ 3 comments… add one }
  • Pickfire March 22, 2016, 1:53 pm

    You can used gzip -k input too.

    • Vivek Gite March 25, 2016, 10:24 am

      Thanks for the tip. The faq has been updated. I appreciate the comment.

  • Student May 9, 2016, 9:05 pm

    Thanks that’s exactly what i was searching for, i find this website to be increasingly useful

Security: Are you a robot or human?

Leave a Comment

You can use these HTML tags and attributes: <strong> <em> <pre> <code> <a href="" title="">


   Tagged with: , ,