Converting images to WebP without losing the originals: anatomy of a Bash script

You have a folder full of photos, screenshots, scans. You want to switch to WebP to save space, but every time you try a script found online you end up with deleted originals, half-corrupted files, or behavior you don’t remember. This script does one thing but does it well: converts images to WebP with ImageMagick, keeps the originals by default, and gives you explicit control over what gets destroyed. No magic, just Bash and ImageMagick.

Let’s look at why it’s built this way and which design choices actually matter.

The starting problem

Batch image conversion is a classic. The naïve solution is one line:

for f in *.jpg; do convert "$f" "${f%.jpg}.webp" && rm "$f"; done

It works until it doesn’t. It breaks on filenames with spaces, deletes originals even when the conversion failed, doesn’t handle images already in WebP, and if you press Ctrl+C halfway through it leaves a half-written .webp behind. On a folder of a thousand photos, one bug means one photo lost forever.

This script solves the problem with a fundamental choice: by default, the originals stay. Destruction is opt-in, explicit, and happens only after the WebP file has been written, verified, and moved into place.

The design choices that make the difference

1. Originals are kept by default

This is the most important difference from the previous version of the script. The DELETE_ORIGINALS=1 flag is defined at the top, but the default behavior is not to delete. To remove originals you must explicitly pass --delete-originals on the command line.

The reason is simple: deleting is irreversible, keeping is not. If something goes wrong during conversion (or if you realize later that the WebP has visible artifacts), the originals are still there. If you did pass --delete-originals, the script deletes only after the WebP file has been verified and moved into place — never before, never halfway.

The documentation in the help is explicit:

--delete-originals  delete original files after conversion (default: no)

A user who reads the help knows exactly what to expect.

2. Writes to a temporary file, moves only on success

Every conversion goes through a temporary file in the same directory:

TMP_OUTPUT="${OUTPUT}.tmp-$$.webp"
"${CMD[@]}" "$FILE" -quality "$WEBP_QUALITY" "$TMP_OUTPUT"

Only if the conversion succeeds, the temporary file is non-empty, and ImageMagick can decode it back does the file get moved into place:

if [[ -f "$TMP_OUTPUT" && -s "$TMP_OUTPUT" ]] \
    && "${CMD[@]}" "$TMP_OUTPUT" -format '%w' info: >/dev/null 2>&1 \
    && mv -f -- "$TMP_OUTPUT" "$OUTPUT"; then

The second check (re-decode) is deliberate: ImageMagick can exit 0 after emitting warnings and still leave a partially decoded file. A non-zero exit is not the only failure mode: warnings plus exit 0 is also a failure mode. The re-decode catches it.

The result: at no point is the destination file half-written. Either it’s a complete, verified WebP, or it doesn’t exist.

3. Never overwrites the source, never overwrites an existing WebP

Two guards before any conversion:

if [[ "$FILE" -ef "$OUTPUT" ]]; then
    # same inode: skip
fi
if [[ -e "$OUTPUT" ]]; then
    # destination exists: skip
fi

The first uses -ef, which compares inodes, not strings. If the source is a symlink pointing to the destination, or path normalization makes them the same file, string comparison would miss it but -ef won’t.

The second prevents silently destroying an existing .webp from a previous run. If you want to re-convert, you delete the .webp first, consciously.

4. Detects ImageMagick v6 vs v7, and verifies WebP support

ImageMagick has two command names in the wild: magick (v7) and convert (v6). The script tries magick first, falls back to convert, and tells you which one it found. Then it checks that the build actually supports WebP:

FORMATS="$("${CMD[@]}" -list format 2>/dev/null || true)"
if ! grep -qiE '^[[:space:]]*webp' <<<"$FORMATS"; then
    T im_no_webp >&2
    exit 1
fi

The regex anchors to the start of the line on purpose. The -list format output contains lines like “Compression options” that also mention “WEBP”, and a naïve grep -i webp would match those too, giving you a false positive. Anchoring to the start of a line ensures you’re matching the actual format row.

If WebP isn’t supported, the script stops immediately instead of failing a thousand times in a row.

5. Traps for interrupt, termination and errors

Three distinct traps:

  • EXIT: cleans up the temporary file if one is left over.
  • INT (Ctrl+C): cleans up and exits with 130.
  • TERM: cleans up and exits with 143.
  • ERR: cleans up, reports the exact line, and exits with 1.

Combined with set -Eeuo pipefail, this means pressing Ctrl+C at any moment never leaves a half-written .webp on disk. The original file, if you didn’t pass --delete-originals, is always intact.

6. Double confirmation before proceeding

Before converting, the script:

  1. Lists every image it found, numbered.
  2. Asks for confirmation with a single-character prompt (s/n or y/n).
  3. Waits for a second ENTER before starting.

Two confirmations might seem excessive, but the difference matters: the first answer confirms the list, the second confirms the start. If you accidentally typed “y” while the list was still scrolling, the second prompt gives you a chance to abort before any file is touched.

The IFS= read -r -t 0.1 _ line after the first answer drains any newline still queued in the terminal, so the second pause really waits for the user instead of consuming the leftover Enter and starting immediately.

7. Handles “difficult” filenames

Three defenses:

  • find -print0 + read -r -d '' handle spaces, newlines, and special characters in names.
  • -H on find follows symlinks given as starting points, so arguments like ./photos -> /mnt/photos are scanned instead of silently yielding nothing.
  • Paths starting with - are prefixed with ./ before being passed to external commands, so a file named -strange.jpg isn’t parsed as a flag.

And there’s a subtle check for names that are only an extension:

if [[ "${file##*/}" == ?*.* ]]; then

This skips a file literally named .jpg (which has no real extension), instead of treating the entire name as the extension. Similarly, a file literally named jpg (no dot) is not treated as a .jpg file.

8. Detects and skips WebP source files

If you pass a .webp file explicitly, the script tells you “already WebP, skipped” and doesn’t try to convert it. This makes the script idempotent: running it twice on the same folder only touches files that actually need conversion.

9. Result summary and exit code

At the end, the script reports:

=== RESULT ===
✅ Converted: 42
❌ Failed: 0
⏭  Skipped: 3
🎉 Operation completed!

The exit code is meaningful: 0 if everything converted or skipped, 1 if any failure occurred. This makes the script usable in scripts and CI pipelines without parsing the human-readable output.

10. i18n with POSIX precedence

The detect_user_language function follows POSIX precedence:

language="${LC_ALL:-${LC_MESSAGES:-${LANG:-en_US}}}"

LC_ALL wins over LC_MESSAGES, which wins over LANG. Only Italian and English are supported, with messages in a single T function with two case blocks. Adding a third language means adding another case. No .po files, no gettext, no dependencies.

11. --help that reflects the current state

The usage() function reads the current values of EXTENSIONS and WEBP_QUALITY and injects them into the help text. If you change WEBP_QUALITY=95 at the top of the script, --help will say “The default WebP quality is 95”. No stale documentation, no guessing.

What it doesn’t do (and that’s fine)

  • No parallelization: one image at a time. For a few hundred images it’s fine; for tens of thousands you’d want xargs -P.
  • No resize or crop: the script only changes the format. It doesn’t touch dimensions.
  • No lossless option: -quality 85 is lossy. If you need lossless WebP, you’ll have to add -define webp:lossless=true, which is a one-line change but not included.
  • No automatic backup beyond the originals: the originals are the backup, until you pass --delete-originals.

How to use it

  1. Install ImageMagick:
    • Arch/CachyOS: pacman -S imagemagick
    • Debian/Ubuntu: sudo apt install imagemagick
    • macOS: brew install imagemagick
  2. Save the script as image2webp.sh and make it executable: chmod +x image2webp.sh.
  3. Adjust WEBP_QUALITY and EXTENSIONS at the top if needed.
  4. Run it:
    • ./image2webp.sh — converts everything under the current directory, keeping the originals.
    • ./image2webp.sh ~/Pictures — converts everything under a specific directory.
    • ./image2webp.sh photo1.jpg photo2.png — converts just those files.
    • ./image2webp.sh --delete-originals ~/Pictures — converts and deletes the originals after verification.

In summary

This script isn’t clever. It’s careful. It keeps originals by default, verifies before moving, never overwrites anything without an explicit request, and cleans up after interrupts. It does the boring work so you can walk away from the terminal while it runs.

The difference from a naïve script isn’t speed: it’s that when something goes wrong, you haven’t lost anything. And if you really want to delete the originals, you say so explicitly, once, with a flag you can’t forget.

If you use it, read it first. If you modify it, keep the golden rules: no deletion without an explicit request, no overwrite without intent, no half-written files, ever. Everything else is negotiable.

Leave a Reply