Gzip – How to Keep Original File

command linefilesgzip

I would like to compress a text file using gzip command line tool while keeping the original file. By default running the following command

gzip file.txt

results in modifying this file and renaming it file.txt.gz. instead of this behavior I would like to have this new compressed file in addition to the existing one file.txt. For now I am using the following command to do that

gzip -c file.txt > file.txt.gz

It works but I am wondering why there is no easier solution to do such a common task ? Maybe I missed the option doing that ?

Best Answer

For GNU gzip 1.6 or above, FreeBSD and derivatives or recent versions of NetBSD, see don_cristi's answer.

With any version, you can use shell redirections as in:

gzip < file > file.gz

When not given any argument, gzip reads its standard input, compresses it and writes the compressed version to its standard output. As a bonus, when using shell redirections, you don't have to worry about files called "--help" or "-" (that latter one still being a problem for gzip -c --).

Another benefit over gzip -c file > file.gz is that if file can't be opened, the command will fail without creating an empty file.gz (or overwriting an existing file.gz) and without running gzip at all.

A significant difference compared to gzip -k though is that there will be no attempt at copying the file's metadata (ownership, permissions, modification time, name of uncompressed file) to file.gz.

Also if file.gz already existed, it will silently override it unless you have turned the noclobber option on in your shell (with set -o noclobber for instance in POSIX shells).

Related Question