I am able to gzip every file in a directory (mydirectory) using the command:

gzip --suffix .gz --recursive mydirectory


  1. I don't want the images (.ico, .jpg, .png, .gif) and PDFs (.pdf) files within the directory to be gzipped.

  2. And those files that are gzipped have the .gz extension. I don't want that. For example, I'd like the gzipped index.html file be index.html itself, and NOT index.html.gz.

So, how do I do this, optimally/efficiently?

Here's how I am doing this now (a pretty lengthy process).

Compress all files in mydirectory but don't delete/replace original files:

cd ~/mydirectory

find . -type f | \
while read -r x
  gzip -c -9 "$x" > "$x.gz"

Remove all gzipped image and PDF files:

find . -type f -iname "*.ico.gz" -exec rm -f {} \;
find . -type f -iname "*.jpg.gz" -exec rm -f {} \;
find . -type f -iname "*.png.gz" -exec rm -f {} \;
find . -type f -iname "*.gif.gz" -exec rm -f {} \;
find . -type f -iname "*.pdf.gz" -exec rm -f {} \;

Rename the existing gzipped files, essentially removing the .gz extension from their name:


for f in `find mydirectory -iname '*.gz'`; do
  mv $f ${f%.gz} 

What we pretty much have now are gzipped text files (.html, .xml, .css, .js) without .gz extension, and uncompressed/un-gzipped images and PDFs.


Step 1: make a backup. Then use find to filter your files and run gzip and then move the file back to the original filename:

find -type f -not \( -iname '*.ico' -or -iname '*.jpg' -or -iname '*.png' -or -iname '*.gif' \) -exec gzip "{}" \; -exec mv "{}.gz" "{}" \;

This is a destructive command so please be careful. Remove the -exec... commands to begin with to make sure it's only selecting files you want to compress.

  • Great, but half the answer. Now all I need is that they don't have the .gz extension (which they do, as of now). – its_me Mar 30 '13 at 13:18
  • @TheoneManis Yeah sorry was struggling with getting the exec to work. Turns out you can add more than one so that fixes everything. – Oli Mar 30 '13 at 13:26
  • Problem! Just checked my site on REDbot, and I saw this error: "This response was compressed using GZip, but the data was corrupt." Is something wrong with the command? (see for yourself: redbot.org/?uri=http%3A%2F%2Faahank.com%2F) – its_me Mar 30 '13 at 17:59
  • Something's really wrong with the command, the way I see it. Other ways I've tried output proper gzipped files. – its_me Mar 31 '13 at 14:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.