bash 中带有空格的回调脚本
我编写了一个小脚本来检查某些内容,如果测试成功,我希望从脚本中执行命令。我不想对命令进行硬编码,而是将其作为参数提供给它,就像回调脚本一样。
我测试的命令是 /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'
时,它看起来像这个,尽管回声看起来是正确的。
当使用 "$1"
而不是 $1
时,它会抱怨找不到该文件。有人知道如何解决空间行为吗?
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
. 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.
When using "$1"
instead of $1
it complains it couldn't find the file. Anyone got ideas how to fix the behavior with the space?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您需要使用数组。
请参阅以下链接,了解如何解决您的问题: 我正在尝试将命令放入变量中,但是复杂的情况总是会失败!
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!
我认为你应该使用
eval
:I think you should use
eval
:尝试 eval "$1" 或重新设计,以便在所有选项之后指定回调 - 常见的安排类似于 script.bash -options 参数等 - /usr/bin/xmessage -按钮“按钮a”,“按钮b”一些要测试的文本
Try
eval "$1"
or redesign so that the callback is specified after all options - a common arrangement would be something likescript.bash -options arguments etc -- /usr/bin/xmessage -buttons "button a","button b" some text to test
我建议你这样编写脚本:
并这样调用它:
I suggest you write the script like this:
And call it like this: