【问题标题】:command does not execute as variable?命令不作为变量执行?
【发布时间】:2014-08-30 18:56:32
【问题描述】:

每当我尝试执行以下 shell 命令时,它都能正常工作。

convert maanavulu_GIST-TLOTKrishna.tif -alpha set -matte -virtual-pixel transparent -set option:distort:viewport 1000x1000 -distort perspective-projection '1.06,0.5,0,0,1.2,0,0,0' -trim 1.jpg

但是,每当我尝试将命令分配给变量然后执行它时,它都会报告以下错误。

convert.im6: invalid argument for option PerspectiveProjection : 'Needs 8 coefficient values' @ error/distort.c/GenerateCoefficients/873.

【问题讨论】:

标签: bash shell imagemagick-convert


【解决方案1】:

简而言之:最好是:

  • 将您的参数存储在一个数组
  • 包括命令本身,以确保安全(最好使用eval 解决方案)
  • 然后用数组调用命令
# Store options in array - note that the filenames are excluded here, too,
# for modularity
opts=(-alpha set -matte -virtual-pixel transparent -set option:distort:viewport \
      1000x1000 -distort perspective-projection '1.06,0.5,0,0,1.2,0,0,0' -trim)

# Invoke command with filenames and saved options
convert maanavulu_GIST-TLOTKrishna.tif "${opts[@]}" 1.jpg

事后考虑:正如@konsolebox 和@chepner 指出的那样:使用函数 可能是最好的选择(固定和可变部分之间的明确分离、封装、全方位的可用的 shell 命令)。

【讨论】:

    【解决方案2】:

    分配和执行命令的正确方法是使用数组:

    COMMAND=(convert maanavulu_GIST-TLOTKrishna.tif -alpha set -matte -virtual-pixel transparent -set option:distort:viewport 1000x1000 -distort perspective-projection '1.06,0.5,0,0,1.2,0,0,0' -trim 1.jpg)
    

    然后执行:

    "${COMMAND[@]}"
    

    我喜欢eval,但这次绝对不是解决方案。

    还有一个提示:如果您可以使用函数,请使用函数。并正确引用你的论点。

    【讨论】:

    • 我认为函数是一个更好的主意。 (您可以在函数体中包含更复杂的 shell 语法;数组仅限于命令和参数的名称:没有管道、没有列表、没有重定向等)
    【解决方案3】:

    扩展变量后不处理引号。发生的唯一处理是分词和通配符扩展。如果您需要执行命令执行的所有正常步骤,则必须使用eval

    eval "$variable"
    

    【讨论】:

    • 如果不知道 OP 在做什么,我不建议使用 eval
    • 虽然我更喜欢他实际展示代码,但我很确定我理解他想要做什么。
    • 有更好的方法将命令行存储在变量中并执行它。
    • @anubhava 请发布一个显示更好方法的答案。
    • 如果variable 是来自外部源的未经验证的输入,则使用eval 是危险的。如果 variable 只是在本地设置为重构代码的一种方式,那么定义一个 shell 函数是更好的主意。 eval 是(或应该是)最后的命令,而不是方便。
    猜你喜欢
    • 2021-02-04
    • 2018-04-02
    • 1970-01-01
    • 2013-02-07
    • 1970-01-01
    • 2021-11-18
    • 2014-08-27
    • 2017-10-03
    • 1970-01-01
    相关资源
    最近更新 更多