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:
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 forgzip -c --
).Another benefit over
gzip -c file > file.gz
is that iffile
can't be opened, the command will fail without creating an emptyfile.gz
(or overwriting an existingfile.gz
) and without runninggzip
at all.A significant difference compared to
gzip -k
though is that there will be no attempt at copying thefile
's metadata (ownership, permissions, modification time, name of uncompressed file) tofile.gz
.Also if
file.gz
already existed, it will silently override it unless you have turned thenoclobber
option on in your shell (withset -o noclobber
for instance in POSIX shells).