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

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

🐧 Get the latest tutorials on SysAdmin, Linux/Unix, Open Source/DevOps topics:
CategoryList of Unix and Linux commands
File Managementcat
FirewallCentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Network Utilitiesdig host ip nmap
OpenVPNCentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Managerapk apt
Processes Managementbg chroot cron disown fg jobs killall kill pidof pstree pwdx time
Searchinggrep whereis which
User Informationgroups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPNCentOS 8 Debian 10 Firewall Ubuntu 20.04

3 comments… add one
  • Pickfire Mar 22, 2016 @ 13:53

    You can used gzip -k input too.

    • 🐧 Vivek Gite Mar 25, 2016 @ 10:24

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

  • Student May 9, 2016 @ 21:05

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

Leave a Reply

Your email address will not be published.

Use HTML <pre>...</pre>, <code>...</code> and <kbd>...</kbd> for code samples.