Way to force gzip not to overwrite files on conflict

command linegzip

I'm writing a script in which I'm gzipping files.

There's a possibility that I might zip a file, create a file of the same name, and try to gzip this as well, e.g.

$ ls -l archive/
total 4
-rw-r--r-- 1 xyzzy xyzzy  0 Apr 16 11:29 foo
-rw-r--r-- 1 xyzzy xyzzy 24 Apr 16 11:29 foo.gz

$ gzip archive/foo
gzip: archive/foo.gz already exists; do you wish to overwrite (y or n)? n   
    not overwritten

By using gzip --force, I can force gzip to overwrite foo.gz, but in this case, I think that there's a good chance that I might lose data if I overwrite foo.gz. There doesn't seem to be a command line switch to force gzip to leave .gz files alone… a non-interactive version of pressing 'n' at the prompt.

I tried gzip --noforce and gzip --no-force, hoping that these might follow the GNU options standard, but neither of these worked.

Is there a straight forward work-around for this?

Edit:

It turns out that this is one of the times that it pays to read the info page rather than the man page.

From the info page:

`--force'
`-f'
     Force compression or decompression even if the file has multiple
     links or the corresponding file already exists, or if the
     compressed data is read from or written to a terminal.  If the
     input data is not in a format recognized by `gzip', and if the
     option `--stdout' is also given, copy the input data without
     change to the standard output: let `zcat' behave as `cat'.  If
     `-f' is not given, and when not running in the background, `gzip'
     prompts to verify whether an existing file should be overwritten.

The man page was missing the text and when not running in the background

When running in the background, gzip will not prompt, and will not overwrite unless the -f option is invoked.

Best Answer

It has dawned on me that the best way to avoid the undesired effect is to not ask the program to perform the undesired effect. That is, simply don't tell it to compress a file if the file is already present in compressed form.

e.g:

if [ ! -f "$file.gz" ]; then 
    gzip "$file"; 
else 
    echo "skipping $file"
fi

or shorter (run true if there is a file.gz, compress file otherwise)

[ -f "$file.gz" ] && echo "skipping $file" || gzip "$file"    
Related Question