Search code examples
bashimagemagick

bash: an option list for convert of Image Magic


I am using convert utility of Image-Magic package integrated into my bash script with the aim to create a 10 x N table conposed of many images sorted into 10 types:

convert \( "${output}/type1.png" -append \) \( "${output}/type2.png" -append \) \( "${output}/type3.png" -append \) ... \( "${output}/type10.png" -append \)  +append -background white -alpha deactivate ${output}/project-summary.png

Since it takes a long line in my bash script I would like to have more control on each block ( "${output}/typeN.png" -append ) in the following fashion:

convert 
\( "${output}/type1.png" -append \) 
#\( "${output}/type2.png" -append \)  # e.g. this type is not included in summary
\( "${output}/type3.png" -append \) 
... 
if [ "${condition}" == 1 ]; then
\( "${output}/type10.png" -append \)  # e.g. this type is included only under condition
elif [ "${condition}" == 2 ]; then
\( "${output}/type11.png" -append \)  # e.g. this type is included only under condition
fi
+append -background white -alpha deactivate ${output}/project-summary.png

I am trying to define a function with a list of elements corresponded to each block of images like:

convert_control() {
opts=( \( "${output}/type1.png" -append \)  )
opts+=( \( "${output}/type2.png" -append \)  )
# opts+=( \( "${output}/type3.png" -append \)  ) # is not included
opts+=( \( "${output}/type4.png" -append \)  )
opts+=( \( "${output}/type5.png" -append \)  )
if [ "${condition}" == 1 ]; then
opts+=( \( "${output}/type10.png" -append \)  ) # included under condition
elif [ "${condition}" == 2 ]; then
opts+=( \( "${output}/type11.png" -append \)  )
fi
}

and then:

convert_control
convert "${opts[@]}" +append -background white -alpha deactivate ${output}/project-summary.png

Any other solutions that could work in the same way in bash ?


Solution

  • Storing your arguments in an array is correct, but I wouldn't define a function for it.

    That said, you can make the code a little nit prettier with:

    opts=(
        \( "$output/type1.png" -append \)
        \( "$output/type2.png" -append \)
    #   \( "$output/type3.png" -append \) # not included in summary
        \( "$output/type4.png" -append \)
        \( "$output/type5.png" -append \)
    )
    case "$condition" in
        1) opts+=( \( "$output/type10.png" -append \) );;
        2) opts+=( \( "$output/type11.png" -append \) );;
    esac