bash 中带有空格的回调脚本

发布于 2025-01-07 09:07:52 字数 562 浏览 2 评论 0原文

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

我测试的命令是 /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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

久隐师 2025-01-14 09:07:53

您需要使用数组。

请参阅以下链接,了解如何解决您的问题: 我正在尝试将命令放入变量中,但是复杂的情况总是会失败!

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!

唔猫 2025-01-14 09:07:53

我认为你应该使用eval

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

I think you should use eval:

#!/bin/bash
echo "$1"
eval $1
无需解释 2025-01-14 09:07:53

尝试 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 like script.bash -options arguments etc -- /usr/bin/xmessage -buttons "button a","button b" some text to test

眼趣 2025-01-14 09:07:52

我建议你这样编写脚本:

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

并这样调用它:

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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文