引用字符串以在命令行中使用

Quoting strings for use in command line

我有一个 for 循环,它构建一个字符串,将其转换为命令行上命令的一系列参数。

循环看起来像:

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

然后我想执行这个命令:

magick "$inputImage" $lineSpecs $outputImage

它应该看起来像:

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

但它失败了,因为字符串被解析为:

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

如何删除错误的引用?

这就是数组的用途。

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 

当然,正如 chepner 在他的回答中所建议的那样,使用数组是最方便的方法,但是如果出于某种原因您必须坚持使用字符串,您可以使用

仔细阅读它
magic $inputImage ${(z)lineSpecs} $outputImage

(z) 负责将字符串正确插入命令行。