I'm trying to use variables in my ImageMagick CLI command to avoid manual text entry. For example, I have a variable set up like this: `ln1='The first line.'` and I'm using it in the command: `convert -pointsize 85 -fill white -draw 'text 40,100 ${ln1}' -draw 'text 40,200 "The second line."' source.jpg out.jpg`. However, I'm confused about how to correctly format this because the single quotes seem to interfere with using variables. I've checked the help documentation but didn't find any examples to clarify. How can I get the variable `ln1` to work properly in this command? Thanks! Also, I've noticed that draw expects single quotes to function correctly, and I'm struggling with making it work even when trying different formats with variables.
4 Answers
What you're dealing with is called *interpolation*. You can only interpolate variables within double quotes in Bash. A workaround for your situation is to use a subshell in your command. Try using `$(echo ...)` to wrap your variable like this: `export ln1="..."; convert ... -draw $(echo "'text 40,200 "${ln1}"'")...` This will allow the variable to be substituted correctly.
Here's how your command should look: `ln1='The first line.'; convert -pointsize 85 -fill white -draw "text 40,100 "${ln1}"" -draw "text 40,200 "The second line."" source.jpg out.jpg`. Using double quotes allows the variable to be evaluated properly. You still need single quotes around the entire draw string, though, for ImageMagick to interpret it right.
Make sure you're not wrapping your variable strings with single quotes, as they prevent any kind of variable expansion. Always prefer double quotes for such cases because anything inside them can be evaluated. So, you should use something like this: `ln1='The first line.'; convert -pointsize 85 -fill white -draw "text 40,100 "${ln1}"" ...`
Thanks for the tip! I'll try that approach.
You should use double quotes for your command since single quotes treat everything inside as literal text. If you need to include double quotes within your drawn text, just escape them with a backslash like this: ". So your command should look something like this: `ln1='The first line.'; convert -pointsize 85 -fill white -draw "text 40,100 "${ln1}"" -draw 'text 40,200 "The second line."' source.jpg out.jpg`.
Got it! I see how escaping works now. Thanks for clarifying!

I appreciate the example! I'll implement this and see how it goes.