{"id":407,"date":"2020-04-16T16:30:00","date_gmt":"2020-04-16T14:30:00","guid":{"rendered":"https:\/\/www.netlabor.it\/?p=407"},"modified":"2026-11-23T01:30:54","modified_gmt":"2026-11-23T00:30:54","slug":"convertire-immagini-in-webp-senza-rischi-anatomia-di-uno-script-bash","status":"publish","type":"post","link":"https:\/\/www.netlabor.it\/en\/convertire-immagini-in-webp-senza-rischi-anatomia-di-uno-script-bash\/","title":{"rendered":"Converting images to WebP without losing the originals: anatomy of a Bash script"},"content":{"rendered":"\n<div class=\"wp-block-bogo-language-switcher\"><\/div>\n\n\n\n<p class=\"wp-block-paragraph\">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&#8217;t remember. This script does one thing but does it well: <strong>converts images to WebP with ImageMagick, keeps the originals by default, and gives you explicit control over what gets destroyed<\/strong>. No magic, just Bash and ImageMagick.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Let&#8217;s look at why it&#8217;s built this way and which design choices actually matter.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">The starting problem<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Batch image conversion is a classic. The na\u00efve solution is one line:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">for f in *.jpg; do convert \"$f\" \"${f%.jpg}.webp\" &amp;&amp; rm \"$f\"; done<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">It works until it doesn&#8217;t. It breaks on filenames with spaces, deletes originals even when the conversion failed, doesn&#8217;t handle images already in WebP, and if you press Ctrl+C halfway through it leaves a half-written <code>.webp<\/code> behind. On a folder of a thousand photos, one bug means one photo lost forever.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">This script solves the problem with a fundamental choice: <strong>by default, the originals stay<\/strong>. Destruction is opt-in, explicit, and happens only after the WebP file has been written, verified, and moved into place.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">The design choices that make the difference<\/h3>\n\n\n\n<h4 class=\"wp-block-heading\">1. Originals are kept by default<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">This is the most important difference from the previous version of the script. The <code>DELETE_ORIGINALS=1<\/code> flag is defined at the top, but the default behavior is <strong>not to delete<\/strong>. To remove originals you must explicitly pass <code>--delete-originals<\/code> on the command line.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">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 <code>--delete-originals<\/code>, the script deletes <strong>only after<\/strong> the WebP file has been verified and moved into place \u2014 never before, never halfway.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The documentation in the help is explicit:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">--delete-originals  delete original files after conversion (default: no)<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">A user who reads the help knows exactly what to expect.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">2. Writes to a temporary file, moves only on success<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Every conversion goes through a temporary file in the same directory:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">TMP_OUTPUT=\"${OUTPUT}.tmp-$$.webp\"\n\"${CMD[@]}\" \"$FILE\" -quality \"$WEBP_QUALITY\" \"$TMP_OUTPUT\"<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">Only if the conversion succeeds, the temporary file is non-empty, <strong>and<\/strong> ImageMagick can decode it back does the file get moved into place:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">if [[ -f \"$TMP_OUTPUT\" &amp;&amp; -s \"$TMP_OUTPUT\" ]] \\\n    &amp;&amp; \"${CMD[@]}\" \"$TMP_OUTPUT\" -format '%w' info: &gt;\/dev\/null 2&gt;&amp;1 \\\n    &amp;&amp; mv -f -- \"$TMP_OUTPUT\" \"$OUTPUT\"; then<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The result: <strong>at no point is the destination file half-written<\/strong>. Either it&#8217;s a complete, verified WebP, or it doesn&#8217;t exist.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">3. Never overwrites the source, never overwrites an existing WebP<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Two guards before any conversion:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">if [[ \"$FILE\" -ef \"$OUTPUT\" ]]; then\n    # same inode: skip\nfi\nif [[ -e \"$OUTPUT\" ]]; then\n    # destination exists: skip\nfi<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The first uses <code>-ef<\/code>, 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 <code>-ef<\/code> won&#8217;t.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The second prevents silently destroying an existing <code>.webp<\/code> from a previous run. If you want to re-convert, you delete the <code>.webp<\/code> first, consciously.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">4. Detects ImageMagick v6 vs v7, and verifies WebP support<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">ImageMagick has two command names in the wild: <code>magick<\/code> (v7) and <code>convert<\/code> (v6). The script tries <code>magick<\/code> first, falls back to <code>convert<\/code>, and tells you which one it found. Then it checks that the build actually supports WebP:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">FORMATS=\"$(\"${CMD[@]}\" -list format 2&gt;\/dev\/null || true)\"\nif ! grep -qiE '^[[:space:]]*webp' &lt;&lt;&lt;\"$FORMATS\"; then\n    T im_no_webp &gt;&amp;2\n    exit 1\nfi<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The regex anchors to the start of the line on purpose. The <code>-list format<\/code> output contains lines like &#8220;Compression options&#8221; that also mention &#8220;WEBP&#8221;, and a na\u00efve <code>grep -i webp<\/code> would match those too, giving you a false positive. Anchoring to the start of a line ensures you&#8217;re matching the actual format row.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">If WebP isn&#8217;t supported, the script stops immediately instead of failing a thousand times in a row.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">5. Traps for interrupt, termination and errors<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Three distinct traps:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>EXIT<\/code>: cleans up the temporary file if one is left over.<\/li>\n\n\n\n<li><code>INT<\/code> (Ctrl+C): cleans up and exits with 130.<\/li>\n\n\n\n<li><code>TERM<\/code>: cleans up and exits with 143.<\/li>\n\n\n\n<li><code>ERR<\/code>: cleans up, reports the exact line, and exits with 1.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">Combined with <code>set -Eeuo pipefail<\/code>, this means <strong>pressing Ctrl+C at any moment never leaves a half-written <code>.webp<\/code> on disk<\/strong>. The original file, if you didn&#8217;t pass <code>--delete-originals<\/code>, is always intact.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">6. Double confirmation before proceeding<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Before converting, the script:<\/p>\n\n\n\n<ol start=\"1\" class=\"wp-block-list\">\n<li>Lists every image it found, numbered.<\/li>\n\n\n\n<li>Asks for confirmation with a single-character prompt (<code>s\/n<\/code> or <code>y\/n<\/code>).<\/li>\n\n\n\n<li>Waits for a second ENTER before starting.<\/li>\n<\/ol>\n\n\n\n<p class=\"wp-block-paragraph\">Two confirmations might seem excessive, but the difference matters: the first answer confirms the <strong>list<\/strong>, the second confirms the <strong>start<\/strong>. If you accidentally typed &#8220;y&#8221; while the list was still scrolling, the second prompt gives you a chance to abort before any file is touched.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>IFS= read -r -t 0.1 _<\/code> 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.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">7. Handles &#8220;difficult&#8221; filenames<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">Three defenses:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><code>find -print0<\/code> + <code>read -r -d ''<\/code> handle spaces, newlines, and special characters in names.<\/li>\n\n\n\n<li><code>-H<\/code> on <code>find<\/code> follows symlinks given as starting points, so arguments like <code>.\/photos -> \/mnt\/photos<\/code> are scanned instead of silently yielding nothing.<\/li>\n\n\n\n<li>Paths starting with <code>-<\/code> are prefixed with <code>.\/<\/code> before being passed to external commands, so a file named <code>-strange.jpg<\/code> isn&#8217;t parsed as a flag.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">And there&#8217;s a subtle check for names that are only an extension:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">if [[ \"${file##*\/}\" == ?*.* ]]; then<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">This skips a file literally named <code>.jpg<\/code> (which has no real extension), instead of treating the entire name as the extension. Similarly, a file literally named <code>jpg<\/code> (no dot) is not treated as a <code>.jpg<\/code> file.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">8. Detects and skips WebP source files<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">If you pass a <code>.webp<\/code> file explicitly, the script tells you &#8220;already WebP, skipped&#8221; and doesn&#8217;t try to convert it. This makes the script idempotent: running it twice on the same folder only touches files that actually need conversion.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">9. Result summary and exit code<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">At the end, the script reports:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">=== RESULT ===\n\u2705 Converted: 42\n\u274c Failed: 0\n\u23ed  Skipped: 3\n\ud83c\udf89 Operation completed!<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">The exit code is meaningful: <strong>0 if everything converted or skipped, 1 if any failure occurred<\/strong>. This makes the script usable in scripts and CI pipelines without parsing the human-readable output.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">10. i18n with POSIX precedence<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>detect_user_language<\/code> function follows POSIX precedence:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">language=\"${LC_ALL:-${LC_MESSAGES:-${LANG:-en_US}}}\"<\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><code>LC_ALL<\/code> wins over <code>LC_MESSAGES<\/code>, which wins over <code>LANG<\/code>. Only Italian and English are supported, with messages in a single <code>T<\/code> function with two <code>case<\/code> blocks. Adding a third language means adding another <code>case<\/code>. No <code>.po<\/code> files, no gettext, no dependencies.<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">11. <code>--help<\/code> that reflects the current state<\/h4>\n\n\n\n<p class=\"wp-block-paragraph\">The <code>usage()<\/code> function reads the current values of <code>EXTENSIONS<\/code> and <code>WEBP_QUALITY<\/code> and injects them into the help text. If you change <code>WEBP_QUALITY=95<\/code> at the top of the script, <code>--help<\/code> will say &#8220;The default WebP quality is 95&#8221;. No stale documentation, no guessing.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What it doesn&#8217;t do (and that&#8217;s fine)<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>No parallelization<\/strong>: one image at a time. For a few hundred images it&#8217;s fine; for tens of thousands you&#8217;d want <code>xargs -P<\/code>.<\/li>\n\n\n\n<li><strong>No resize or crop<\/strong>: the script only changes the format. It doesn&#8217;t touch dimensions.<\/li>\n\n\n\n<li><strong>No lossless option<\/strong>: <code>-quality 85<\/code> is lossy. If you need lossless WebP, you&#8217;ll have to add <code>-define webp:lossless=true<\/code>, which is a one-line change but not included.<\/li>\n\n\n\n<li><strong>No automatic backup beyond the originals<\/strong>: the originals are the backup, until you pass <code>--delete-originals<\/code>.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\">How to use it<\/h3>\n\n\n\n<ol start=\"1\" class=\"wp-block-list\">\n<li>Install ImageMagick:\n<ul class=\"wp-block-list\">\n<li>Arch\/CachyOS: <code>pacman -S imagemagick<\/code><\/li>\n\n\n\n<li>Debian\/Ubuntu: <code>sudo apt install imagemagick<\/code><\/li>\n\n\n\n<li>macOS: <code>brew install imagemagick<\/code><\/li>\n<\/ul>\n<\/li>\n\n\n\n<li>Save the script as <code>image2webp.sh<\/code> and make it executable: <code>chmod +x image2webp.sh<\/code>.<\/li>\n\n\n\n<li>Adjust <code>WEBP_QUALITY<\/code> and <code>EXTENSIONS<\/code> at the top if needed.<\/li>\n\n\n\n<li>Run it:\n<ul class=\"wp-block-list\">\n<li><code>.\/image2webp.sh<\/code> \u2014 converts everything under the current directory, <strong>keeping the originals<\/strong>.<\/li>\n\n\n\n<li><code>.\/image2webp.sh ~\/Pictures<\/code> \u2014 converts everything under a specific directory.<\/li>\n\n\n\n<li><code>.\/image2webp.sh photo1.jpg photo2.png<\/code> \u2014 converts just those files.<\/li>\n\n\n\n<li><code>.\/image2webp.sh --delete-originals ~\/Pictures<\/code> \u2014 converts and <strong>deletes the originals<\/strong> after verification.<\/li>\n<\/ul>\n<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\">In summary<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">This script isn&#8217;t clever. It&#8217;s <strong>careful<\/strong>. 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.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">The difference from a na\u00efve script isn&#8217;t speed: it&#8217;s that when something goes wrong, <strong>you haven&#8217;t lost anything<\/strong>. And if you really want to delete the originals, you say so explicitly, once, with a flag you can&#8217;t forget.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">If you use it, read it first. If you modify it, keep the golden rules: <strong>no deletion without an explicit request, no overwrite without intent, no half-written files, ever<\/strong>. Everything else is negotiable.<\/p>\n\n\n\n<div class=\"wp-block-file\"><a id=\"wp-block-file--media-7aaf1790-e383-46b1-a970-319664f30625\" href=\"https:\/\/www.netlabor.it\/netlabor\/wp-content\/uploads\/2026\/11\/image2webp.sh_.zip\">Convert any image to WebP format<\/a><a href=\"https:\/\/www.netlabor.it\/netlabor\/wp-content\/uploads\/2026\/11\/image2webp.sh_.zip\" class=\"wp-block-file__button wp-element-button\" download aria-describedby=\"wp-block-file--media-7aaf1790-e383-46b1-a970-319664f30625\">Download<\/a><\/div>\n\n\n\n<p class=\"wp-block-paragraph\"><\/p>\n","protected":false},"excerpt":{"rendered":"<p>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&#8217;t remember. This script does one thing but does it well: converts images to WebP with ImageMagick, [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"full-width-page-template.php","format":"standard","meta":{"_locale":"en_US","_original_post":"https:\/\/www.netlabor.it\/?p=385","footnotes":""},"categories":[34,14,6,7],"tags":[35,15,8,9],"class_list":["post-407","post","type-post","status-publish","format-standard","hentry","category-2d","category-grafica","category-informatica","category-programmazione","tag-2d","tag-grafica","tag-informatica","tag-programmazione","en-US","missing-thumbnail"],"_links":{"self":[{"href":"https:\/\/www.netlabor.it\/wp-json\/wp\/v2\/posts\/407","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.netlabor.it\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.netlabor.it\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.netlabor.it\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.netlabor.it\/wp-json\/wp\/v2\/comments?post=407"}],"version-history":[{"count":1,"href":"https:\/\/www.netlabor.it\/wp-json\/wp\/v2\/posts\/407\/revisions"}],"predecessor-version":[{"id":408,"href":"https:\/\/www.netlabor.it\/wp-json\/wp\/v2\/posts\/407\/revisions\/408"}],"wp:attachment":[{"href":"https:\/\/www.netlabor.it\/wp-json\/wp\/v2\/media?parent=407"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.netlabor.it\/wp-json\/wp\/v2\/categories?post=407"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.netlabor.it\/wp-json\/wp\/v2\/tags?post=407"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}