简体   繁体   English

bash中带有空格的回调脚本

[英]callback script with space in bash

I wrote a little script that check something, and i want a command to be executed from within the script if the test was successfull. 我编写了一个检查某些内容的小脚本,如果测试成功,我希望从脚本中执行命令。 And i don't want to hardcode the command, but give it as argument to it like a callback script. 而且我不想对命令进行硬编码,而是像回调脚本一样将其作为参数提供。

The command I testing with is /usr/bin/xmessage -buttons "button a","button b" some text to test . 我测试的命令是/usr/bin/xmessage -buttons "button a","button b" some text to test Running it within a terminal standalone works fine, no quotation marks needed for the last text. 在终端机上独立运行它可以正常工作,最后一个文本不需要引号。

The script looks like this: 该脚本如下所示:

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

But when running /path/to/script.bash '/usr/bin/xmessage -buttons "button a","button b" some text to test' it looks like this , though the echo looks right. 但是,当运行/path/to/script.bash '/usr/bin/xmessage -buttons "button a","button b" some text to test'它看起来像这样 ,尽管回声看起来正确。

When using "$1" instead of $1 it complains it couldn't find the file. 当使用"$1"而不是$1它抱怨找不到文件。 Anyone got ideas how to fix the behavior with the space? 有人知道如何解决空间问题吗?

You'll need to use an array. 您将需要使用数组。

See the following link on how to fix your problem: I'm trying to put a command in a variable, but the complex cases always fail! 有关如何解决问题的信息,请参见以下链接: 我试图将命令放入变量中,但是复杂的情况总是会失败!

I think you should use eval : 我认为您应该使用eval

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

I suggest you write the script like this: 我建议您这样编写脚本:

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

And call it like this: 并这样称呼它:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM