Search code examples
bashif-statementimagemagick

bash + image-magick: if condition inside the program call


My bash script calls convert utility of the Image-magic to stack together several types of the input images depending on the provided condition:

if [ "$DETAILS" == 1 ]; then
#stack 3 types of images in vertical row
convert \( "${output}/${target}*.png" -bordercolor lightgoldenrod2 -border 0x2 -append \) \( "${output}/${dist}*.png" -bordercolor lightgoldenrod2 -border 0x2 -append \) \( "${output}/${angl}*.png" -bordercolor lightgoldenrod2 -border 0x2 -append \) -bordercolor lightgoldenrod2 -border 2x0 +append -background white -alpha deactivate ${output}/HBONDS-summary.png
else
   #stack 1 type of images in vertical row
convert \( "${output}/${target}*.png" -bordercolor lightgoldenrod2 -border 0x2 -append \) -bordercolor lightgoldenrod2 -border 2x0 +append -background white -alpha deactivate ${output}/HBONDS-summary.png
fi

Since the difference between two options is just the number of the blocks

\( .. \)

provided for convert, would it be possible rather to put the IF condition INSIDE the convert to simplify the script e.g. this could be a wrong bash syntax but the general idea may be:

 # Add two more blocks with ${dist} and ${angl} images if we match the condition:
convert \( "${output}/${target}*.png" -bordercolor lightgoldenrod2 -border 0x2 -append \) **!NB >>> if [ "$DETAILS" == 1 ];** then \( "${output}/${dist}*.png" -bordercolor lightgoldenrod2 -border 0x2 -append \) \( "${output}/${angl}*.png" **fi;** <<< -bordercolor lightgoldenrod2 -border 0x2 -append \) -bordercolor lightgoldenrod2 -border 2x0 +append -background white -alpha deactivate ${output}/HBONDS-summary.png

Solution

  • You can do something like this:

    convert_extra_args=()
    if [ "$DETAILS" == 1 ]; then
      convert_extra_args=(
        \( "${output}/${dist}*.png" -bordercolor lightgoldenrod2 -border 0x2 -append \)
        \( "${output}/${angl}*.png" -bordercolor lightgoldenrod2 -border 0x2 -append \)
      )
    fi
    
    convert \( "${output}/${target}*.png" -bordercolor lightgoldenrod2 -border 0x2 -append \) "${convert_extra_args[@]}" -bordercolor lightgoldenrod2 -border 2x0 +append -background white -alpha deactivate ${output}/HBONDS-summary.png