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).
Gzip works only with a single file, or a stream - data piped to gzip. So you first need to generate one file, like with tar, and then you could gzip that. The other option is to gzip all individual files, and then tar that into one file.
Both these solutions are stupid and should not be used. You should use tar with the built in compression option and do it all in one command.
Best Answer
This does NOT work:
This is a race condition:
The problem is that the
> example.txt
(ordd of=example.txt
for that matter) kills the file before the other process has the chance to read it. So there is no obvious solution, which is why you should stick tomv
.There are a number of ways you could cheat. You can open the file, then unlink it - the file will continue to exist until you close it - and then create a new file with the same name and write the gzipped data to that. However I do not know an obvious way to coerce bash to use that, and even if I did, my answer would still be:
Don't even do it.
If
gzip
fails for any reason, or any problem occurs, like you running out of space while gzipping (because other processes are writing, or gzip result is larger than the input - which happens for random data - etc.), you just lost your file. Congratulations!Create a separate file and
mv
on success. That's the simplest, easy to understand, and most reliable method you will ever find.