title: Running shell script loop in parallel
body: <p>I wrote an shell script which</p>
  
  <ol>
  <li>get list of all image files from directory</li>
  <li>create new folder if needed for new image</li>
  <li>optimize image in order to save storage resources</li>
  </ol>
  
  <p>I've tried to use <code>parallel -j "$(nproc)"</code> before <code>mogrify</code> but found that it was wrong, because before mogrify is used DIR and mkdir, i need instead something like <code>&amp;</code> at end of <code>mogrify</code> but to do it only for <code>n</code> processes.</p>
  
  <p>the current code look like:</p>
  
  <pre><code>#!/bin/bash
  
  find $1 -iname "*.jpg" -o -iname "*.jpeg" -o -iname "*.png" -o -iname "*.gif" -type f | while read IMAGE
  do
      DIR="$2"/`dirname $IMAGE`
      echo "$IMAGE &gt; $DIR"
      mkdir -p $DIR
      mogrify -path "$DIR" -resize "6000000@&gt;" -filter Triangle -define filter:support=2 -unsharp 0.25x0.08+8.3+0.045 -dither None -posterize 136 -quality 82 -define jpeg:fancy-upsampling=off -define png:compression-filter=5 -define png:compression-level=9 -define png:compression-strategy=1 -define png:exclude-chunk=all -interlace none -colorspace sRGB "$IMAGE"
  done
  
  exit 0
  </code></pre>
  
  <p>Can someone suggest what will be the right way to run such script in parallel? as each run take about 15 seconds.</p>