Connor
Connor

Reputation: 4844

Quoting strings for use in command line

I have a for loop that builds up a string to be converted to a series of arguments for a command on the command line.

the loop looks like:

lineSpecs=""
for tripWire in {1..$numTrips}
do
  lineSpec="-stroke ${colors[$tripWire+1]:0} -draw 'stroke-width 3 line $topX,$topY $botX,$botY'"
    
  lineSpecs="${lineSpecs} ${lineSpec}"
done

I then want to execute this command with:

magick "$inputImage" $lineSpecs $outputImage

It should look like:

magick 'input.jpeg' -stroke purple -draw 'stroke-width 3 line 69,188 304,387' -stroke red -draw 'stroke-width 3 line 176,158 429,303' PaintedImage.jpg

but it fails because the string is parsed as:

magick 'input.jpeg' ' -stroke purple -draw '\''stroke-width 3 line 69,188 304,387'\'' -stroke red -draw '\''stroke-width 3 line 176,158 429,303'\' PaintedImage.jpg

How to remove the erroneous quoting?

Upvotes: 0

Views: 49

Answers (2)

user1934428
user1934428

Reputation: 22225

Of course using an array, as chepner suggested in his answer, is the most convenient approach, but if for whatever reason you have to stick with your string, you can peruse it with

magic $inputImage ${(z)lineSpecs} $outputImage

The (z) takes care of interpolating the string properly into the command line.

Upvotes: 1

chepner
chepner

Reputation: 530823

This is what arrays are for.

lineSpecs=()
for tripWire  in {1..$numTrips}
do
  lineSpec+=(-stroke ${colors[$tripWire+1]:0} -draw "stroke-width 3 line $topX,$topY $botX,$botY"')    
done

magic "$inputImage" $lineSpecs $outputImage 

Upvotes: 1

Related Questions