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


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

Posted by: SXI ADMIN

The author is the creator of nixCraft and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.


How to KVM, QEMU start or stop virtual machine from command line (CLI)

KVM or Kernel Based Virtual Machine is a popular virtualization technology. It allows you to run virtual guest machines over a host machine. To start...

How to Docker backup Saving and restoring your volumes

Running a Docker volume backup First, we spin up a temporary container, and we mount the backup folder and the target Docker volume to this container....

How to Start and Enable Firewalld on CentOS 7

In this article, we discuss how to start and enable firewalld. It is highly recommended that you have a firewall protecting your server.Pre-Flight CheckThese...