【问题标题】:How to properly quote spaces when building a string of options in Ash / Bash?在 Ash / Bash 中构建一串选项时如何正确引用空格?
【发布时间】:2020-07-30 15:40:33
【问题描述】:
livy@linux:~$ qemu_options="-enable-kvm -name \"Virtual Machine 1\"";
livy@linux:~$ qemu_options="$qemu_options -cpu host -smp cores=4 -m 2G";
livy@linux:~$ echo "$qemu_options";
-enable-kvm -name "Virtual Machine 1" -cpu host -smp cores=4 -m 2G
livy@linux:~$ qemu-system-x86_64 $qemu_options;
qemu-system-x86_64: Machine: Could not open 'Machine': No such file or directory

我已经尝试并成功地保留了 Virtual Machine 1 字符串周围的引号。为什么它不起作用?以及如何正确引用?

【问题讨论】:

  • 使用 bash 数组。
  • @KamilCuk 尽管我的 shell 是 Bash,但我总是尝试编写与 ash 兼容的代码以使其可移植。然而,ash 中没有可用的数组。
  • 然后使用位置参数。喜欢set -- -enable-kvm -name ...; qemu-system-x86_64 "$@"

标签: bash sh ash


【解决方案1】:

为什么它不起作用?

因为在其他扩展的未引用结果上识别出引号后执行分词。扩展的内容不扫描,只拆分。

如何正确引用?

使用 bash 数组。

如果没有,请使用函数。

如果您已经用尽了任何其他替代方案,请使用 eval 输入黑暗面,并正确地双引号引用参数并在调用时重新评估它们。请记住,eval 距离邪恶只有一个字母。

qemu_options="$(printf " %q" -enable-kvm -name "Virtual Machine 1")"
qemu_options+="$(printf " %q" -cpu host -smp cores=4 -m 2G")"
eval qemu-system-x86_64 "$qemu_options"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-22
    • 1970-01-01
    • 1970-01-01
    • 2014-03-31
    • 1970-01-01
    • 2016-09-18
    • 1970-01-01
    • 2018-09-14
    相关资源
    最近更新 更多