【问题标题】:command line arguments fed from an array从数组馈送的命令行参数
【发布时间】:2016-04-26 11:39:48
【问题描述】:

我想执行一个复杂的 bash 命令,使用从长数组提供的数据作为参数。我想它必须以某种方式使用子shell。

例如,代替可行的 convert -size 100x100 xc:black -fill white -draw "point 1,1" -draw "point 4,8" -draw "point 87,34" etc etc etc image.png

我想采用不同的逻辑,其中参数在同一命令中给出,更像

convert -size 100x100 xc:black -fill white $(for i in 1,1 4,8 87,34 etc etc; -draw "point $i"; done) image.png 这不起作用,因为 $i 被解释为包含参数的命令。

请注意,“for i in ...; do convert ...$i...; done”将不起作用。 -draw "point x,y" 系列参数必须在同一个运行 convert 命令中,因为 convert 不接受现有图像中的 -draw 参数。

【问题讨论】:

  • 您需要 echo/printf 来自嵌入式 -draw ... 循环的 -draw ... 字符串。

标签: bash for-loop parameter-passing imagemagick-convert


【解决方案1】:

首先构建一个-draw 参数数组。

for pt in 1,1 4,8 87,34; do
    points+=(-draw "point $pt")
done
convert -size 100x100 xc:black -fill white "${points[@]}" image.png

【讨论】:

    【解决方案2】:

    您可以通过使用@ 文件说明符后跟代表stdin 的破折号将MVG 绘图命令通过其stdin 泵入convert 来保持命令行简洁明了,如下所示:

    for i in 1,1 4,8 87,34; do 
       echo point $i
    done | convert -size 100x100 xc:red -draw @- result.png
    

    或者,如果您有一个名为 points 的数组:

    points=(1,1 4,8 87,34)
    
    printf "point %s\n" ${points[@]} | convert -size 100x100 xc:red -draw @- result.png
    

    【讨论】:

      【解决方案3】:

      尝试像这样使用扩展而不是子shell:

      echo -draw\ \"point\ {1\,1,2\,2,3\,3}\"
      

      产生这个输出:

      -draw "point 1,1" -draw "point 2,2" -draw "point 3,3"
      

      【讨论】:

      • 这使得-draw "point 1,1" 成为一个单独的参数,而不是covert 期望的两个单独的参数-drawpoint 1,1
      【解决方案4】:

      printf扩展内容怎么样?

      points=(1,1 4,8 87,34)
      printf -- '-draw "point %s" ' ${points[@]}
      

      返回以下字符串(末尾没有新行):

      -draw "point 1,1" -draw "point 4,8" -draw "point 87,34"
      

      你可以说:

      points=(1,1 4,8 87,34)
      convert ... "$(printf -- '-draw "point %s" ' ${points[@]})" image.png
      #           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      

      这样,您将点存储在一个数组中,然后printf 将其“传递”给convert 命令。

      【讨论】:

      • 谢谢,不过语法是-draw "point x,y",带有破折号。当我尝试printf '-draw ...' printf 将其识别为 -d 选项并返回错误。我尝试使用语法printf ' -draw ...' 解决它,然后,我不知道为什么,convert 将其识别为文件名并返回convert: unable to open image -draw "point etc`
      • @Voprosnik 避免printf 理解-d 作为选项的方法是在其后添加--,因此它知道不再提供参数--> printf -- '-draw "point %s" ' ${points[@]}。跨度>
      猜你喜欢
      • 2019-12-12
      • 2012-10-04
      • 1970-01-01
      • 1970-01-01
      • 2010-11-03
      • 2012-03-15
      • 2016-07-02
      • 2017-04-16
      • 1970-01-01
      相关资源
      最近更新 更多