【问题标题】:callback script with space in bashbash 中带空格的回调脚本
【发布时间】:2012-02-20 17:48:16
【问题描述】:

我写了一个小脚本来检查一些东西,如果测试成功,我希望从脚本中执行一个命令。而且我不想对命令进行硬编码,而是像回调脚本一样将其作为参数提供给它。

我测试的命令是/usr/bin/xmessage -buttons "button a","button b" some text to test。在独立终端中运行它可以正常工作,最后一个文本不需要引号。

脚本如下所示:

#!/bin/bash
echo "$1"
$1

但是当运行/path/to/script.bash '/usr/bin/xmessage -buttons "button a","button b" some text to test' 时,它看起来像this,虽然回显看起来正确。

当使用"$1" 而不是$1 时,它会抱怨找不到文件。有人知道如何解决空间行为吗?

【问题讨论】:

    标签: linux bash callback arguments


    【解决方案1】:

    我建议你这样写脚本:

    #!/bin/bash
    echo ${1+"$@"}
    ${1+"$@"}
    

    然后这样称呼它:

    /path/to/script.bash /usr/bin/xmessage -buttons "button a","button b" some text to test
    

    【讨论】:

    • 如果命令是脚本的第二个参数,这个可以用吗?
    • 是的。所有参数都存储在$@ 中,${1+"$@"} 是在脚本中使用它们的完美方式。
    • 我的意思是script.sh otherarg1 otherarg2 callback
    • 这种情况下需要${1+"${@:3}"}
    【解决方案2】:

    你需要使用一个数组。

    请参阅以下链接了解如何解决您的问题:I'm trying to put a command in a variable, but the complex cases always fail!

    【讨论】:

      【解决方案3】:

      我认为你应该使用eval:

      #!/bin/bash
      echo "$1"
      eval $1
      

      【讨论】:

        【解决方案4】:

        尝试eval "$1" 或重新设计,以便在所有选项之后指定回调 - 常见的安排类似于script.bash -options arguments etc -- /usr/bin/xmessage -buttons "button a","button b" some text to test

        【讨论】:

        • 重新设计时如何调用回调?
        • 基本上shift 去掉主要参数,然后运行"$@",这基本上就是@Ade 的回复。
        猜你喜欢
        • 1970-01-01
        • 2014-06-05
        • 2013-04-01
        • 2012-11-15
        • 1970-01-01
        • 1970-01-01
        • 2015-10-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多