8

I want to unzip .gz files but without overwriting. When the resulting file exists, gunzip will ask for permission to overwrite, but I want gunzip not to overwrite by default and just abort. I read in a man that -f force overwriting, but I haven't found nothing about skipping it.

gunzip ${file} 

I need something like -n in copying cp -n ${file}

Chris Maes
  • 35,025
  • 12
  • 111
  • 136
herder
  • 412
  • 2
  • 5
  • 16

3 Answers3

26

gunzip will prompt you before overwriting a file. You can use the yes command to automatically send an n string to the gunzip prompt, as shown below:

$ yes n | gunzip file*.gz
gunzip: file already exists;    not overwritten
gunzip: file2 already exists;    not overwritten
dogbane
  • 266,786
  • 75
  • 396
  • 414
8

Granting your files have .gz extensions, you can check if the file exists before running gunzip:

[[ -e ${file%.gz} ]] || gunzip "${file}"

[[ -e ${file%.gz} ]] removes .gz and checks if a file having its name exists. If not (false), || would run gunzip "${file}".

konsolebox
  • 72,135
  • 12
  • 99
  • 105
3

Here's a combination of the answers here and this that will unzip a group of gzipped files to a different destination directory:

dest="unzipped"
for f in *.gz; do
  STEM=$(basename "${f}" .gz)
  unzipped_name="$dest/$STEM"
  echo ''
  echo gunzipping $unzipped_name
  if [[ -e $unzipped_name ]]; then
    echo file exists
  else
    gunzip -c "${f}" > $unzipped_name
    echo done
  fi
done
Community
  • 1
  • 1
crizCraig
  • 8,487
  • 6
  • 54
  • 53