Skip to content

Replacing files in place

Sometimes you want to optimize files in place — no _timestamp copies, no separate output directory. That’s what --replace is for, and it’s designed to be safe.

Terminal window
imgsqz photo.jpg --replace -q 80

This re-encodes photo.jpg and writes the smaller result back to photo.jpg.

A naive “overwrite in place” is dangerous: if the process dies mid-write, you’re left with a truncated, corrupt file. imgsqz avoids this:

  1. Encode the optimized image to a temporary file next to the target: photo.jpg.imgsqz.tmp.
  2. Once the temp file is fully written, atomically rename it over the original (fs.rename).

A rename is atomic on a single filesystem, so at no point is photo.jpg a half-written file. If imgsqz is interrupted before step 2, your original is untouched — you just have a stray .imgsqz.tmp you can delete.

--replace keeps the file in place but the extension follows the format. If you convert, you get a new file alongside the original name pattern:

Terminal window
# Re-encode and keep as JPG, in place
imgsqz photo.jpg --replace -q 78
# "Replace" but convert to webp → writes photo.webp (the .jpg still exists)
imgsqz photo.jpg --replace -f webp

--replace works across many inputs (unlike --output):

Terminal window
# Optimize every JPG in place
imgsqz *.jpg --replace -q 80 --quiet

This is the canonical “shrink this whole folder of photos in place” command.

GoalCommand
Keep original, make a timestamped copy (default)imgsqz photo.jpg
Keep original, clean output nameimgsqz photo.jpg --no-timestamp -o photo-opt.jpg
Overwrite the original in placeimgsqz photo.jpg --replace
Write to a separate folderimgsqz photo.jpg -o out/photo.jpg

Next: the full CLI reference.